使用本机管道将预测与 mutate 结合使用

问题描述 投票:0回答:3

我想在 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

r dplyr
3个回答
2
投票

像这样使用

dplyr::cur_data
怎么样?

newDF <- newDF |> 
    mutate(prediction = predict(mod, cur_data()))

2
投票

看起来 cur_data() 在 dplyr 1.1.0 中已被弃用,现在可以使用 pick() 来代替:

newDF <- newDF |> 
  mutate(prediction = predict(mod, pick(x)))

0
投票

这里也可以进行简单的选择:

newDF <- newDF |> 
  mutate(prediction = predict(mod, select(., x)))
© www.soinside.com 2019 - 2024. All rights reserved.