How to rescale value in a loop based

Dear all,

I have these columns in an excel file:
N_GEN CAPTURE CUM_ADULTI_SV CUM_ADULTI_G1 CUM_ADULTI_G2 A1 A2 A3
1 0 0,1 0,01 0,001 1 0,1 0,3
1 1 0,5 0,1 0,05 2 0,5 0,8
1 0 1 0,5 0,1 2,5 1 1
1 5 1,2 0,8 0,5 3 1,5 1,2
2 1 1,5 1 0,9 4 2 1,8
2 2 1,8 1,2 1 5 3 2
2 7 2 1,5 1,1 5,5 3,2 2,1
2 9 2,1 1,6 1,2 5,6 3,5 2,9
3 1 2,2 1,7 1,5 6 4 3
3 2 2,5 2 1,8 7 5 4
3 7 3 3 3 9 7 5
3 10 3,5 4 3,5 9,3 8 6

I have to create a new column in this dataframe through a loop of functions like this:
A1[1](sum(capture[group_by N_GEN 1])/(sum(A1[group_by N_GEN1])
A1[2]
(sum(capture[group_by N_GEN 1])/(sum(A1[group_by N_GEN1])
A1[3]*(sum(capture[group_by N_GEN 1])/(sum(A1[group_by N_GEN1])
ecc... based on generation number

I tried with this function:
DB1 <- for(x in DB$N_GEN){
if(x == 1) {
mutate(AR1 = DB$CUM_ADULTI_SV*(sum(DB$CAPTURE)/sum(DB$A1)))
} else if (x == 2) {
mutate(AR2 = DB$CUM_ADULTI_G1*(sum(DB$CAPTURE)/sum(DB$A2)))
} else {
mutate(AR3 = DB$CUM_ADULTI_G2*(sum(DB$CAPTURE)/sum(DB$A3)))
}
}
DB1

But it doesnt give me any good results
Thanks

In general it works best if you

  • follow the advice in the FAQ
  • specify the exact error you get

Do you mean something like this:

library(dplyr)
library(tibble)

db1 <- tibble::tribble(
~N_GEN, ~CAPTURE, ~CUM_ADULTI_SV, ~CUM_ADULTI_G1, ~CUM_ADULTI_G2, ~A1, ~A2, ~A3,
1, 0, 0.1, 0.01, 0.001, 1, 0.1, 0.3,
1, 1, 0.5, 0.1, 0.05, 2, 0.5, 0.8,
1, 0, 1, 0.5, 0.1, 2.5, 1, 1,
1, 5, 1.2, 0.8, 0.5, 3, 1.5, 1.2,
2, 1, 1.5, 1, 0.9, 4, 2, 1.8,
2, 2, 1.8, 1.2, 1, 5, 3, 2,
2, 7, 2, 1.5, 1.1, 5.5, 3.2, 2.1,
2, 9, 2.1, 1.6, 1.2, 5.6, 3.5, 2.9,
3, 1, 2.2, 1.7, 1.5, 6, 4, 3,
3, 2, 2.5, 2, 1.8, 7, 5, 4,
3, 7, 3, 3, 3, 9, 7, 5,
3, 10, 3.5, 4, 3.5, 9.3, 8, 6
)

db2 <- db1 |>
  group_by(N_GEN) |>
  mutate(AR1 = CUM_ADULTI_SV*(sum(CAPTURE)/sum(A1)),
         AR2 = CUM_ADULTI_G1*(sum(CAPTURE)/sum(A2)),
         AR3 = CUM_ADULTI_G2*(sum(CAPTURE)/sum(A3))
         )

See the FAQ for how to put you question in a form that makes it easier to attract answers, beginning with avoiding having to create the data frame.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.