Reputation: 23
I've the following dataframe:
df <- structure(list(locality_id = structure(c(3L, 1L, 2L, 4L), .Label = c("L2762894",
"L3064193", "L6199859", "L8044094"), class = "factor"), month = structure(c(1L,
3L, 1L, 2L), .Label = c("1", "2", "3"), class = "factor"), prec01 = c(105,
109, 133, 79), prec02 = c(29, 34, 34, 35), prec03 = c(18, 48,
42, 184)), class = "data.frame", row.names = c(NA, -4L))
Each locality
has precipitation
values for the first three months
(prec01, prec02, prec03)
.
I would like to create an unique precipitation column matching the corresponding precipitation value of each month to the corresponding month (column month). Resulting in something as follows:
# locality_id month prec
# 1 L6199859 1 105
# 2 L2762894 3 109
# 3 L3064193 1 133
# 4 L8044094 2 184
Any idea of how to do produce the above output?
Thank you!
Upvotes: 0
Views: 43
Reputation: 920
If I understood your question you want to keep in the new prec
column the corresponding value of precXX
for that month
?
In that case it seems to me that the example is not correct, but should instead be:
Starting dataframe:
locality_id month prec01 prec02 prec03
1 L6199859 1 105 29 18
2 L2762894 3 109 34 48
3 L3064193 1 133 34 42
4 L8044094 2 79 35 184
Final dataframe:
locality_id month prec
1 L6199859 1 105
2 L2762894 3 48
3 L3064193 1 133
4 L8044094 2 35
You may achieve that with matrix indexing:
i <- as.numeric(df$month)
df$prec <- df[,c(3,4,5)][cbind(seq_along(i), i)]
df[,c(-3,-4,-5)]
Upvotes: 1