按没收拆分,并用NA填充

时间:2019-02-19 20:24:36

标签: r

如何在不使用任何循环的情况下从第一个表(table1)获取第二个表(table2)?

table1 <- data.frame(stringsAsFactors=FALSE,
           x = c("1,2,3"),
           y = c("a,b,c,d"),
           z = c("e,f"))
table1

|x     |y       |z   |
|:-----|:-------|:---|
|1,2,3 |a,b,c,d |e,f |

table2 <- data.frame(stringsAsFactors=FALSE,
           x = c(1, 2, 3, NA),
           y = c("a", "b", "c", "d"),
           z = c("e", "f", NA, NA))
table2

|  x|y  |z  |
|--:|:--|:--|
|  1|a  |e  |
|  2|b  |f  |
|  3|c  |NA |
| NA|d  |NA |

Tabla 1

Tabla 2

2 个答案:

答案 0 :(得分:0)

这是我尝试使用基数R的解决方案;

x = data.frame(x="1,2,3", y="a,b,c,d", z="e,f", stringsAsFactors = F)

# split each column by the comma
x2 = lapply(x, function(x) strsplit(x, ",")[[1]])

# find the max length of the column
L = max(sapply(x2, length))

# make all the columns equal that length i.e. fill the missing with NA 
x3 = lapply(x2, function(x) { length(x) = L; x })

# cbind them all together and turn into dataframe
x4 = data.frame(do.call(cbind, x3))

虽然很长。我希望看到一个更好的解决方案。

答案 1 :(得分:0)

您可以使用stringr包来实现此目的

table1 <- data.frame(stringsAsFactors=FALSE,
                     x = c("1,2,3"),
                     y = c("a,b,c,d"),
                     z = c("e,f"))

t(stringr::str_split_fixed(table1, pattern = ",", max(stringr::str_count(table1, ","))+1))
#>      [,1] [,2] [,3]
#> [1,] "1"  "a"  "e" 
#> [2,] "2"  "b"  "f" 
#> [3,] "3"  "c"  ""  
#> [4,] ""   "d"  ""

reprex package(v0.2.0)于2019-02-20创建。

将其分解为单独的步骤

  1. 通过计算每列中的逗号数,找到最大的列数并加1(因为项目数比逗号数多1),找到列的最大长度。

max(stringr::str_count(table1, ","))+1

  1. 使用str_split_fixed在逗号处拆分每列,并根据上一步中的str_count()使用最大列数。这将用NA填充多余的列。

stringr::str_split_fixed(table1, pattern = ",", max(stringr::str_count(table1, ","))+1)

  1. 使用t()转置表格,使其处于所需格式。

t(stringr::str_split_fixed(table1, pattern = ",", max(stringr::str_count(table1, ","))+1))