【发布时间】:2020-02-12 09:25:56
【问题描述】:
我在这里寻求帮助。我有两个数据框,df1 和 df2。我想根据 df2 中特定行的总和向 df1 添加一个额外的列。
Df1 包含站名。 Df2 包含位置、年份和以度为单位的观测值。我想要每个站的度数总和。这些学位应该是每年特定地点的总和。 可以将其想象为“每个站点都应根据给定的位置,每年获得其度数之和”。我希望只编码站名和位置,desired_output 中的年份应该包括 df2 中给出的所有年份。
失败的示例和所需的输出。我更喜欢在 tidyverse 环境中工作。
一切顺利
df1 <- data.frame(station = c("station_A", "station_B"))
df2 <- data.frame(location= c("south", "north", "north", "east", "west"), year = c(2000, 2000, 2001, 2001, 2001), degrees = c(5,3,9,5,2))
degrees_for_each_station <-
df1%>%
mutate (degrees = case_when(
station == "station_A" ~ if_else(df2$location %in% c("north","south"),
sum(df2$degrees),
NA),
station == "station_B" ~ if_else(df2$location %in% c("north","east", "west"),
sum(df2$degrees),
NA)))
desired_output <- data.frame(station = c("station_A", "station_A","station_B", "station_B"),
year = c(2000, 2001, 2000, 2001),
degrees = c(8,9,3,16))```
【问题讨论】: