I have a data frame with a column of models and I am trying to add a column of predicted values to it. A minimal example is :
exampleTable <- data.frame(x = c(1:5, 1:5),
y = c((1:5) + rnorm(5), 2*(5:1)),
groups = rep(LETTERS[1:2], each = 5))
models <- exampleTable %>% group_by(groups) %>% do(model = lm(y ~ x, data = .))
exampleTable <- left_join(tbl_df(exampleTable), models)
estimates <- exampleTable %>% rowwise() %>% do(Est = predict(.$model, newdata = .["x"]))
How can I add a column of numeric predictions to exampleTable
? I tried using mutate
to directly add the column to the table without success.
exampleTable <- exampleTable %>% rowwise() %>% mutate(data.frame(Pred = predict(.$model, newdata = .["x"])))
Error: no applicable method for 'predict' applied to an object of class "list"
Now I use bind_cols
to add the estimates
to exampleTable
but I am looking for a better solution.
estimates <- exampleTable %>% rowwise() %>% do(data.frame(Pred = predict(.$model, newdata = .["x"])))
exampleTable <- bind_cols(exampleTable, estimates)
How can it be done in a single step?
See Question&Answers more detail:os