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.
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, .)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With