分离数据只针对前n个实例

12

我在R中有一个data.frame,为了简单起见,该数据框只有一列需要分离。它长这样:

V1
Value_is_the_best_one
This_is_the_prettiest_thing_I've_ever_seen
Here_is_the_next_example_of_what_I_want

我的真实数据非常庞大(数百万行),因此我想使用tidyr的separate函数(因为它非常快)仅分离出前几个实例。我希望结果如下:

V1       V2     V3     V4 
Value    is     the    best_one
This     is     the    prettiest_thing_I've_ever_seen
Here     is     the    next_example_of_what_I_want

正如您所看到的,分隔符是_,V4列可以有不同数量的分隔符。我想保留V4(不要丢弃它),但不必担心里面有多少内容。始终会有四列(即我的行中没有只包含V1-V3的行)。

这是我一直在使用的起始tidyr命令:

separate(df, V1, c("V1", "V2", "V3", "V4"), sep="_")

这将消除V4(并发出警告,但这不是最大的问题)。


3
你只需要 extra = "merge" 吗? - aosmith
@aosmith 是的,谢谢。我已经读了文档大约10遍,但总是误解了它!请把它写成答案吧! - Gaius Augustus
2个回答

34

您需要在 "merge" 选项中使用 extra 参数。这样可以仅允许定义的新列数量作为拆分数。

separate(df, V1, c("V1", "V2", "V3", "V4"), extra = "merge")

     V1 V2  V3                             V4
1 Value is the                       best_one
2  This is the prettiest_thing_I've_ever_seen
3  Here is the    next_example_of_what_I_want

如果你想要反向合并呢?比如说,你有一个字符串"John Q Public.",我想把它分成两个字符串:"John Q"和"Public."。除了手动拆分和子集化之外,是否有一种简单的方法来实现这个目标? - David Bruce Borenstein
1
@DavidBruceBorenstein 似乎您需要设置 sep 参数,以便仅在最后一个空格处拆分。 - aosmith

6

这里有另外一种使用 extract 的选项。

library(tidyr)
extract(df1, V1, into = paste0("V", 1:4), "([^_]+)_([^_]+)_([^_]+)_(.*)")
#      V1 V2  V3                             V4
# 1 Value is the                       best_one
# 2  This is the prettiest_thing_I've_ever_seen
# 3  Here is the    next_example_of_what_I_want

另一个选择是使用stringi库中的stri_split函数,我们可以指定拆分的数量。

library(stringi)
do.call(rbind, stri_split(df1$V1, fixed="_", n=4))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接