tidyr separate only first n instances [duplicate]

江枫思渺然 提交于 2019-11-28 00:51:17

问题


This question already has an answer here:

  • How to strsplit different number of strings in certain column by do function 1 answer

I have a data.frame in R, which, for simplicity, has one column that I want to separate. It looks like this:

V1
Value_is_the_best_one
This_is_the_prettiest_thing_I've_ever_seen
Here_is_the_next_example_of_what_I_want

My real data is very large (millions of rows), so I'd like to use tidyr's separate function (because it's amazingly fast) to separate out JUST the first few instances. I'd like the result to be the following:

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

As you can see, the separator is _ the V4 column can have different numbers of the separators. I want to keep V4 (not discard it), but not have to worry about how much stuff is in there. There will always be four columns (i.e. none of my rows have only V1-V3).

Here is my starting tidyr command I've been working with:

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

This gets rid of V4 (and spits out warnings, which isn't the biggest deal).


回答1:


You need the extra argument with the "merge" option. This allows only as many splits as you have new columns defined.

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



回答2:


Here is another option with 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

Another option is stri_split from library(stringi) where we can specify the number of splits

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


来源:https://stackoverflow.com/questions/37126634/tidyr-separate-only-first-n-instances

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!