I have a dataframe:
Station | Day | Precip |
---|---|---|
A | 1 | w |
A | 2 | x |
B | 1 | y |
B | 3 | z |
And I need to create a new data frame with the values in the Day column as the new column headers:
Station | 1 | 2 | 3 |
---|---|---|---|
A | w | x | |
B | y | z |
I tried subsetting, summarizing, and then merging.
df1 <- subset(df, DAY == "1")
df2 <- subset(df, DAY == "2")
df3 <- subset(df, DAY == "3")
df1 <- df1 %>% group_by(STATION) %>% summarise(DAY_1 = sum(Precip))
df2 <- df2 %>% group_by(STATION) %>% summarise(DAY_2 = sum(Precip))
df3 <- df3 %>% group_by(STATION) %>% summarise(DAY_3 = sum(Precip))
df_grouped <- merge(df1, df2, all = TRUE)
df_grouped <- merge(df_grouped, df3, all = TRUE)
This does what I want, but I'm sure there's probably an easier way. I would greatly appreciate any thoughts. Thank you!