【发布时间】:2023-03-12 19:37:01
【问题描述】:
我有两个数据框 df 和 df2。我想通过过滤df2在df中生成一个新列,这样过滤器就依赖于df。相反,可以使用 for 循环,但这对于大数据帧来说非常慢......请查看代码。 提前非常感谢
法比安
#generating dummy data frames
df <- data.frame("var1" = 0:15)
df2 <- data.frame("var2" = 11:20, "var3" = 21:30)
# the following command unfortunatelly does not work
df$new_column <- df2 %>% filter(var2 > df$var1) %>% mean(var3)
# that's the output I want - but without a for-loop
for (i in 1:length(df$var1)){
h <- df2 %>% filter(var2 > df$var1[i])
df$new_column[i] <- mean(h$var3)
}
【问题讨论】: