根据模式将data.table列拆分为许多未知的列数

时间:2017-09-03 07:36:02

标签: r string 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

1 个答案:

答案 0 :(得分:4)

我们可以使用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)]

更新

由于,列中未考虑numeric,我们会将其删除并与type.convert = TRUE中的tstrsplit分开

dt1[, paste0("B", seq_len(M)) := tstrsplit(gsub(",", "", B), " ",
         fixed = TRUE, type.convert = TRUE)]