Home > Net >  Use predict with mutate using native pipe
Use predict with mutate using native pipe

Time:03-31

I would like to predict a new column onto the current df within a dplyr chain. Tried:

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.

How can I reference field x within my dply chain like this using the native pipe?

CodePudding user response:

How about using dplyr::cur_data like this?

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