【发布时间】:2020-02-25 07:07:39
【问题描述】:
您好,我想将 data.frame 的一列拆分为多列,但将连续的分隔符视为一列。我的输入是从文本文件中抓取的,所以使用不同的分隔符有点混乱,有时同一个分隔符会重复多次。在下面的示例中,我使用了空格、逗号、 “和”或破折号作为分隔符,但实际上我有超过 6 个不同的分隔符,包括几个单词(“and”和“incl”)。
我通常会使用tidyr::separate,但它没有组合连续分隔符的选项。试图列出该模式的可能组合的详尽列表很快就会变得荒谬,尤其是有时我可能连续有 4 或 5 个空格或逗号。
我在下面提供了一个代表和所需的输出(通过手动更改文本,这在我的 1000 行的真实数据中是不可行的)
数据:
library(tidyr)
testdf <- data.frame(test = c("This string has single spaces",
"This one has double spaces",
"This, has, comma,or space, or ,both",
"This,one-, space,- comma -,and-dash"))
这些是我目前尝试使用的代码:
separate(testdf, test, into = letters[1:12], sep = " |,|-|and", fill = "right")
#> Warning: Expected 12 pieces. Additional pieces discarded in 2 rows [3, 4].
#> a b c d e f g h i j k l
#> 1 This string has single spaces <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 2 This one has double spaces <NA> <NA> <NA>
#> 3 This has comma or space
#> 4 This one space comma
#sort of starting to work but gets very extensive very fast
separate(testdf, test, into = letters[1:12], sep = " |, |, | |and|,", fill = "right")
#> a b c d e f g h i j k l
#> 1 This string has single spaces <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 2 This one has double spaces <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 3 This has comma or space or both
#> 4 This one- space - comma - -dash <NA> <NA>
根据 Gregor 在我指定之前的回答,我需要单词分隔符:
separate(testdf, test, into = letters[1:12], sep = "[ ,-]+", fill = "right")
#> a b c d e f g h i j k l
#> 1 This string has single spaces <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 2 This one has double spaces <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 3 This has andcomma or and space or both <NA> <NA> <NA> <NA>
#> 4 This one space and comma and dash <NA> <NA> <NA> <NA> <NA>
###*Desired Output:*
```r
#> a b c d e f g
#> 1 This string has single spaces <NA> <NA>
#> 2 This one has double spaces <NA> <NA>
#> 3 This has comma or space or both
#> 4 This one space comma dash <NA> <NA>
由reprex package (v0.3.0) 于 2019 年 10 月 30 日创建
【问题讨论】:
-
\\s+|,|-只处理多个空格,而不是其他空格的组合或倍数。 -
我对您的更新感到困惑 - 如果
and是分隔符,为什么它仍在您想要的结果中(第 4 行)? -
哦,这是一个错字/我没有彻底做出我想要的输出
标签: r regex string split tidyr