【发布时间】:2021-05-23 16:45:59
【问题描述】:
这里的一个无私的成员帮助我编写了以下代码,以使用 for 循环和 dplyr::summarize 生成变量。正如预期的那样,这段代码运行良好。
library(nycflights13)
flights <- nycflights13::flights %>%
select(carrier,distance,hour)
by_carrier <- NULL
for ( i in c("distance", "hour") {
df <-
flights %>%
dplyr::group_by(carrier) %>%
dplyr::summarize(!!as.name(i) := sum(!!as.name(i) ))
by_carrier <- bind_cols(by_carrier,df)
}
但是当我按以下方式更改for循环参数时,会遇到错误:
var_interest <- c("distance", "hour")
by_carrier <- NULL
for ( i in seq_along(var_interest)) {
df <-
flights %>%
dplyr::group_by(carrier) %>%
dplyr::summarize(!!as.name(i) := sum(!!as.name(i) ))
by_carrier <- bind_cols(by_carrier,df)
}
错误如下:
Error: Problem with `summarise()` input `1`.
x object '1' not found
i Input `1` is `sum(`1`)`.
i The error occurred in group 1: carrier = "9E".
Run `rlang::last_error()` to see where the error occurred.
我在这里缺少什么?提前致谢。
【问题讨论】:
标签: r for-loop dplyr rlang summarize