我有以下测试数据:
structure(list(testcode = structure(1:3, .Label = c("1", "20",
"300"), class = "factor"), testname = structure(c(2L, 3L, 1L), .Label = c("Bed",
"Book", "Car"), class = "factor")), .Names = c("testcode", "testname"
), row.names = c(NA, -3L), class = "data.frame")
我有一个函数,可以标识特定的列名称,然后将前导零作为字符添加到该列中的变量中。 (所有列都是字符)。由于“code”列中的列变量具有可变长度,因此我认为使用paste0作为paste0("0",column_name)
是最简单的。
功能如下:
library(dplyr)
fix_codes <- function(df) {
code_column <- grep("code$", colnames(df), value = TRUE)
df <- df %>%
mutate_at(.vars = code_column, .funs = funs(paste0("0",code_column)))
return(df)
}
但是,paste0 似乎不明白我想要将 code_column 指定的列粘贴在一起,而不是像现在一样粘贴“code_column”本身。如何让paste0正确识别它?
我想要的结果是:
testcode testname
01 Book
020 Car
0300 Bed
最佳答案
我们可以使用.
来代替对所选列的实际值应用粘贴
fix_codes <- function(df) {
code_column <- grep("code$", colnames(df), value = TRUE)
df <- df %>%
mutate_at(.vars = code_column, .funs = funs(paste0("0",.)))
return(df)
}
df
# testcode testname
#1 1 Book
#2 20 Car
#3 300 Bed
fix_codes(df)
# testcode testname
#1 01 Book
#2 020 Car
#3 0300 Bed
使用 lapply
的等效基本 R 方法也是我们直接选择列的地方
df[grep("code$", colnames(df))][] <-
lapply(df[grep("code$", colnames(df))], function(x) paste0("0", x))
关于r - 使用 mutate_at 中的粘贴添加到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50367231/