根据模式将data.table列拆分为许多未知数量的列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据模式将data.table列拆分为许多未知数量的列相关的知识,希望对你有一定的参考价值。
我想根据它的值之间的空格将B
data.table
的列dt1
分成许多列。
df1 <-
structure(list(B = c("3,845,168 15,467,645 15,054,813 913 30,523,371",
"3,104,154 12,495,278 12,298,236 223 24,793,737", "741,014 2,972,367 2,756,577 690 5,729,634",
"218,044 1,035,308 1,008,748 18 2,044,074", "200,744 961,775 942,901 13 1,904,689",
"17,300 73,533 65,847 5 139,385"), C = c("17,743,645", "14,456,435",
"3,287,210", "1,165,692", "1,071,138", "94,554"), D = c("102.74",
"101.60", "107.83", "102.63", "102.00", "111.67"), E = c("2.89",
"2.87", "2.96", "2.99", "3.07", "2.06")), .Names = c("B", "C",
"D", "E"), row.names = c(NA, -6L), class = "data.frame"
)
library(data.table)
dt1 <- data.table(df1)
dt1
B C D E
1: 3,845,168 15,467,645 15,054,813 913 30,523,371 17,743,645 102.74 2.89
2: 3,104,154 12,495,278 12,298,236 223 24,793,737 14,456,435 101.60 2.87
3: 741,014 2,972,367 2,756,577 690 5,729,634 3,287,210 107.83 2.96
4: 218,044 1,035,308 1,008,748 18 2,044,074 1,165,692 102.63 2.99
5: 200,744 961,775 942,901 13 1,904,689 1,071,138 102.00 3.07
6: 17,300 73,533 65,847 5 139,385 94,554 111.67 2.06
答案
我们可以使用tstrsplit
tmp <- dt1[, tstrsplit(B, "\s+")]
dt1[, paste0("B", seq_along(tmp)) := tmp]
rm(tmp)
或者@DavidArenburg提到,我们可以通过首先从stri_count_fixed
找到stringi
的空格数然后使用tstrsplit
和fixed = TRUE
参数来避免创建临时对象
M <- max(stringi::stri_count_fixed(dt1$B, " ")) + 1
dt1[, paste0("B", seq_len(M)) := tstrsplit(B, " ", fixed = TRUE)]
Update
由于,
不在numeric
列中考虑,我们删除它并与type.convert = TRUE
中的tstrsplit
分开
dt1[, paste0("B", seq_len(M)) := tstrsplit(gsub(",", "", B), " ",
fixed = TRUE, type.convert = TRUE)]
以上是关于根据模式将data.table列拆分为许多未知数量的列的主要内容,如果未能解决你的问题,请参考以下文章