这是我的解决方案。
输入:
v1 <- c(3, 5.5, 9)
v2 <- c("x", "y", "z")
foo <- data.table(col1 = 1:10, col2 = sample(letters[1:5], replace = TRUE))
N_col0 <- NCOL(foo) # used later on to redefine column class
代码:
v12 <- c(rbind(v1, v2))
m12 <- matrix(rep(v12, each = NROW(foo)), NROW(foo))
foo <- cbind(foo, m12)
numeric_col <- grep("[0-9]", v12) + N_col0
for(j in numer_col){set(foo, j=j, value=as.numeric(foo[[j]]))}
代码解释:
1.结合 v1 和 v2。
v12 <- c(rbind(v1, v2)) # note it is a character vector
print(v12)
[1] "3" "x" "5.5" "y" "9" "z"
2.创建v12的字符矩阵。如果您愿意,可以在此阶段设置列名。
m12 <- matrix(rep(v12, each = NROW(foo)), NROW(foo))
print(v12)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "3" "x" "5.5" "y" "9" "z"
[2,] "3" "x" "5.5" "y" "9" "z"
[3,] "3" "x" "5.5" "y" "9" "z"
[4,] "3" "x" "5.5" "y" "9" "z"
[5,] "3" "x" "5.5" "y" "9" "z"
[6,] "3" "x" "5.5" "y" "9" "z"
[7,] "3" "x" "5.5" "y" "9" "z"
[8,] "3" "x" "5.5" "y" "9" "z"
[9,] "3" "x" "5.5" "y" "9" "z"
[10,] "3" "x" "5.5" "y" "9" "z"
3.c绑定 foo & m12.
foo<- cbind(foo, m12)
print(foo)
col1 col2 V1 V2 V3 V4 V5 V6
1: 1 b 3 x 5.5 y 9 z
2: 2 d 3 x 5.5 y 9 z
3: 3 d 3 x 5.5 y 9 z
4: 4 e 3 x 5.5 y 9 z
5: 5 d 3 x 5.5 y 9 z
6: 6 b 3 x 5.5 y 9 z
7: 7 d 3 x 5.5 y 9 z
8: 8 d 3 x 5.5 y 9 z
9: 9 e 3 x 5.5 y 9 z
10: 10 d 3 x 5.5 y 9 z
4.所有新列都是字符列。为了解决这个问题,我们可以检测向量 12 中哪些元素是数字的,并使用数据表的函数集。
foo[, lapply(.SD, class)]
col1 col2 V1 V2 V3 V4 V5 V6
1: integer character character character character character character character
numeric_col <- grep("[0-9]", v12) + N_col0
for(j in numer_col){set(foo, j=j, value=as.numeric(foo[[j]]))}
foo[, lapply(.SD, class)]
col1 col2 V1 V2 V3 V4 V5 V6
1: integer character numeric character numeric character numeric character