Raivo Kolde Raivo Kolde -4 years ago 109
R Question

dplyr calculate new columns in batch

I would like to add new columns to a data.frame using dplyr. One by one it is easy using

mutate
. However, I have a situation where I have a function that calculates several parameters based on some other column and I would like to add them to the table in one go. Suppose I have a function

f = function(x) {data.frame(A = x + 1, B = x + 2, C = x + 3)}


And I want to run this function against a column in a data.frame and add the results to the same data.frame, so

df = data.frame(x = 1:10)
df %>% XXX(f(x))


would result in data.frame like this:

x A B C
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
6 7 8 9
7 8 9 10
8 9 10 11
9 10 11 12
10 11 12 13


I know I have read about function like
XXX
in the example above, but I'm unable to find it right now. Anybody has hints?

Answer Source

We can use do

library(dplyr)
df %>% 
  do(data.frame(., f(.$x)))
#    x  A  B  C
#1   1  2  3  4
#2   2  3  4  5
#3   3  4  5  6
#4   4  5  6  7
#5   5  6  7  8
#6   6  7  8  9
#7   7  8  9 10
#8   8  9 10 11
#9   9 10 11 12
#10 10 11 12 13

Or

library(purrr)
df %>%
    map_df(f) %>%
    bind_cols(df, .)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download