bjorn2bewild
bjorn2bewild

Reputation: 1019

Generating multiple columns at once with dplyr

I often have to dynamically generate multiple columns based on values in existing columns. Is there a dplyr equivalent of the following?:

cols <- c("x", "y")
foo <- c("a", "b")
df <- data.frame(a = 1, b = 2)
df[cols] <- df[foo] * 5

> df
  a b x  y
1 1 2 5 10

Upvotes: 3

Views: 315

Answers (1)

NelsonGon
NelsonGon

Reputation: 13319

Not the most elegant:

library(tidyverse)
df %>% 
  mutate_at(vars(foo),function(x) x*5) %>% 
   set_names(.,nm=cols) %>% 
   cbind(df,.)
  a b x  y
1 1 2 5 10

This can be made more elegant as suggested by @akrun :

df %>%
 mutate_at(vars(foo), list(new = ~ . * 5)) %>% 
 rename_at(vars(matches('new')), ~ c('x', 'y'))

Upvotes: 3

Related Questions