Nicholas Root
Nicholas Root

Reputation: 555

mutate multiple columns generated with one function?

Suppose I have a data frame with any number of variables, plus 3 variables for an RGB color. I want to convert the RGB color to LAB, and add these to the data frame. Here's the ugly code:

df <- data.frame(id=c(1:10),red=runif(10),green=runif(10),blue=runif(10))
df <- cbind(df,convertColor(subset(df,select=c("red","green","blue")),from="sRGB",to="Lab"))

It would be great if mutate could generate multiple variables with a single call; e.g. (pseudocode):

df <- data.frame(id=c(1:10),red=runif(10),green=runif(10),blue=runif(10))
df <- df %>% mutate(list("L","a","b") = convertColor(cbind(red,green,blue),from="sRGB",to="Lab"))

Is there a similar approach using dplyr?

Upvotes: 4

Views: 1583

Answers (2)

eddi
eddi

Reputation: 49448

If you want to avoid needless copying of your data, this is the data.table syntax, to add the new columns by modifying your data in place:

library(data.table)
dt = as.data.table(df)

dt[, c('L', 'a', 'b') := as.data.table(convertColor(.SD, from = 'sRGB', to = 'Lab'))
   , .SDcols = c('red', 'green', 'blue')]

Upvotes: 2

Marat Talipov
Marat Talipov

Reputation: 13304

If you want some syntactic sugar, you can use this code:

df %>% 
  select(red,green,blue) %>% 
  convertColor(from="sRGB",to="Lab") %>% 
  cbind(df,.)

Upvotes: 2

Related Questions