r - tidyr 仅分离前 n 个实例

标签 r tidyr

这个问题在这里已经有了答案:





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

(1 个回答)


3年前关闭。




我在 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 的单独函数(因为它非常快)来分离出前几个实例。我希望结果如下:
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(并发出警告,这不是最大的问题)。

最佳答案

您需要 extra"merge" 的争论选项。这仅允许与定义的新列一样多的拆分。

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

关于r - tidyr 仅分离前 n 个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126634/

相关文章:

r - 尽管安装并加载了reshape2,仍找不到“cast”功能

r - 如何基于两列扩展数据框?

将长数据 reshape 为多个宽列

r - 列出 R 中数据帧的元素

r - 更改 networkD3 图的背景颜色

r - 基于多列进行拆分,然后在 R 中应用 spread()

python - 将分块文件读入数据帧

r - "Multi-step"在 R 中使用 broom 和 dplyr 进行回归

r - 填充 R data.frame 中每行中缺失的元素

r - 如何使用 facet_grid 或 facet_wrap 保持条的厚度均匀并切换 strip 位置?