小编典典

将数据框字符串列拆分为多列

all

我想获取表格的数据

before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
  attr          type
1    1   foo_and_bar
2   30 foo_and_bar_2
3    4   foo_and_bar
4    6 foo_and_bar_2

并在上面split()的“”列上使用type以获得如下内容:

  attr type_1 type_2
1    1    foo    bar
2   30    foo  bar_2
3    4    foo    bar
4    6    foo  bar_2

我想出了一些令人难以置信的复杂的东西,涉及某种形式的apply工作,但后来我放错了地方。这似乎太复杂了,不是最好的方法。我可以strsplit如下使用,但不清楚如何将其恢复到数据框中的
2 列中。

> strsplit(as.character(before$type),'_and_')
[[1]]
[1] "foo" "bar"

[[2]]
[1] "foo"   "bar_2"

[[3]]
[1] "foo" "bar"

[[4]]
[1] "foo"   "bar_2"

感谢您的任何指示。我还没有完全了解 R 列表。


阅读 67

收藏
2022-04-20

共1个答案

小编典典

采用stringr::str_split_fixed

library(stringr)
str_split_fixed(before$type, "_and_", 2)
2022-04-20