我想在 dplyr 链中预测当前 df 上的新列。尝试过:
library(tidyverse)
mod <- lm(price ~ x, data = diamonds)
newDF <- data.frame(x = rnorm(10, mean = mean(diamonds$x)))
newDF <- newDF |>
mutate(prediction = predict(mod, .$x)) # object '.' not found
newDF <- newDF |>
mutate(\(.) prediction = predict(mod, .$x)) # `..1` must be a vector, not a function.
如何使用本机管道在我的 dply 链中引用字段
x
?
像这样使用
dplyr::cur_data
怎么样?
newDF <- newDF |>
mutate(prediction = predict(mod, cur_data()))
看起来 cur_data() 在 dplyr 1.1.0 中已被弃用,现在可以使用 pick() 来代替:
newDF <- newDF |>
mutate(prediction = predict(mod, pick(x)))
这里也可以进行简单的选择:
newDF <- newDF |>
mutate(prediction = predict(mod, select(., x)))