改变用一个函数生成的多列?

mutate multiple columns generated with one function?

假设我有一个包含任意数量变量的数据框,外加 3 个 RGB 颜色变量。我想将 RGB 颜色转换为 LAB,并将它们添加到数据框中。这是丑陋的代码:

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"))

如果 mutate 可以通过一次调用生成多个变量,那就太好了;例如(伪代码):

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"))

是否有使用 dplyr 的类似方法?

如果你想要一些语法糖,你可以使用这段代码:

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

如果你想避免不必要的数据复制,这是 data.table 语法,通过修改你的数据来添加新列:

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')]