2

Given

base <- data.frame( a = 1) 
f <- function() c(2,3,4)

I am looking for a solution that would result in a function f being applied to each row of base data frame and the result would be appended to each row. Neither of the following works:

result <- base %>% rowwise() %>% mutate( c(b,c,d) = f() )
result <- base %>% rowwise() %>% mutate( (b,c,d) = f() )
result <- base %>% rowwise() %>% mutate( b,c,d = f() )

What is the correct syntax for this task?

This appears to be a similar problem (Assign multiple new variables on LHS in a single line in R) but I am specifically interested in solving this with functions from tidyverse.

user2530062
  • 427
  • 4
  • 14

2 Answers2

4

I think the best you are going to do is a do() to modify the data.frame. Perhaps

base %>% do(cbind(., setNames(as.list(f()), c("b","c","d"))))

would probably be best if f() returned a list in the first place for the different columns.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thank you! The complete solution with parameter in f() would be then: `base <- data.frame( a = c(1,2))` `f <- function(x) data.frame(b = 2*x, c = 3*x, d= 4*x)` `base %>% do(cbind(., f(.$a)))` – user2530062 Dec 21 '17 at 11:54
  • In my scenario `rowwise()` was still required before `do` (despite the example solution above works without it). – user2530062 Jan 02 '18 at 13:45
0

In case you're willing to do this without dplyr:

# starting data frame
base_frame <- data.frame(col_a = 1:10, col_b = 10:19)

# the function you want applied to a given column 
add_to <- function(x) { x + 100 } 

# run this function on your base data frame, specifying the column you want to apply the function to:
add_computed_col <- function(frame, funct, col_choice) {
  frame[paste(floor(runif(1, min=0, max=10000)))] = lapply(frame[col_choice], funct)
  return(frame)
}

Usage:

df <- add_computed_col(base_frame, add_to, 'col_a')
head(df)

enter image description here

And add as many columns as needed:

df_b <- add_computed_col(df, add_to, 'col_b')
head(df_b)

enter image description here

Rename your columns.

Cybernetic
  • 12,628
  • 16
  • 93
  • 132