Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign multiple columns from lapply() using dplyr and tibble

Tags:

r

dplyr

tibble

I have a case in which I'd like to enhance the code to be more straight, assigning multiple elements of lapply's results as columns for tibble.

I know how do this for data.table, the operation would be like this:

data <- data.table(x = 1:9)
data[,  c("y","z") := lapply(2:3, function(p) x ^ p)]

#   x  y   z
#1: 1  1   1
#2: 2  4   8
#3: 3  9  27
#4: 4 16  64
#5: 5 25 125

Now, I'd like to do the same with dplyr. I have already tried alternatives, for example:

data <- tibble(x = 1:9)
data <- data %>% 
            mutate(c("y","z") = lapply(2:3, function(p) x ^ p))

but it goes wrong.

like image 823
Rafael Toledo Avatar asked Sep 17 '25 21:09

Rafael Toledo


1 Answers

We can use the tidyverse option

library(tidyverse)
map2(2:3, c("y", "z"), ~set_names(data_frame(data$x^.x), .y)) %>%
            bind_cols(data, .)   
#   x  y   z
#1: 1  1   1
#2: 2  4   8
#3: 3  9  27
#4: 4 16  64
#5: 5 25 125
#6: 6 36 216
#7: 7 49 343
#8: 8 64 512
#9: 9 81 729

Or we can remove the data_frame call

data %>%
     map2(2:3, ~ .^.y) %>%
     set_names(., c("y", "z")) %>%
     bind_cols(data, .)
like image 154
akrun Avatar answered Sep 19 '25 12:09

akrun