dplyr - row_number in mutate in a for loop

28 views Asked by At

Good evening,

I am new in R so this might be an easy question.

I have a dataframe, df, similar to the following:

station date day1 day2 day3 . . . day365 a 0101 100 200 300 . . . 400 a 0201 100 200 300 . . . 400 a 0301 100 200 300 . . . 400 . . . . . . . . . a 3112 100 200 300 . . . 400
b 0101 150 170 250 . . . 500 b 0201 150 170 250 . . . 500 b 0301 150 170 250 . . . 500 . . . . . . . . . a 3112 150 170 250 . . . 500

In other words, each station is observed 365 days and there are 365 columns, one for each day where each column has duplicate values for each station.

I would like to create the variable "day" in the following way:

station date day a 0101 100 a 0201 200 a 0301 300 b 0101 150 b 0201 170 b 0301 250

I tried using the following code in r:

for(i in 1:365) {
 colnum <- 2+i
 df <- df %>%
  group_by(station) %>%
  mutate(day = ifelse(row_number()==i, df[i, colnum], day))
}

This seems to work only for the first station but not for the following stations: would you know how to solve this?

Thank you in advance!

0

There are 0 answers