我想使用dplyr::mutate
创建新的数据框列,使用自定义函数,其参数是数据框列名称的向量,但我得到了以下输出:
customFun <- function(col.vec) {
paste0(gsub("\\s", "_", col.vec), collapse = "-")
}
df <- data.frame(A = c("x 1", "x", "x w"), B = c("E", "D", "2 w"), stringsAsFactors = FALSE)
df %>%
mutate(C = customFun(c(A, B)))
A B C
1 x 1 E x_1-x-x_w-E-D-2_w
2 x D x_1-x-x_w-E-D-2_w
3 x w 2 w x_1-x-x_w-E-D-2_w
使用以下内容代替:
data.table::data.table(df)[, C := customFun(c(A, B)), by = .(A, B)]
A B C
1: x 1 E x_1-E
2: x D x-D
3: x w 2 w x_w-2_w
有很多种方法可以实现,但我只对dplyr
解决方案感兴趣。感谢您的帮助。
with(head(iris),customFun(c(Species, Petal.Length, Petal.Width)))
,你会发现这不是你想要的。c(Species, Petal.Length, Petal.Width)
已经是一个向量,因此在技术上不能与另一个不存在的东西粘贴在一起。 - Onyambudf%>%mutate(C = invoke(paste,data.frame(gsub('\\s+','_',as.matrix(.))),sep='-'))
的操作。 - Onyambu