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

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

我想要获取表格的数据


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列表。


千万里不及你
浏览 667回答 4
4回答

不负相思意

另一种选择是使用新的tidyr包。library(dplyr)library(tidyr)before <- data.frame(&nbsp; attr = c(1, 30 ,4 ,6 ),&nbsp;&nbsp; type = c('foo_and_bar', 'foo_and_bar_2'))before %>%&nbsp; separate(type, c("foo", "bar"), "_and_")##&nbsp; &nbsp;attr foo&nbsp; &nbsp;bar## 1&nbsp; &nbsp; 1 foo&nbsp; &nbsp;bar## 2&nbsp; &nbsp;30 foo bar_2## 3&nbsp; &nbsp; 4 foo&nbsp; &nbsp;bar## 4&nbsp; &nbsp; 6 foo bar_2

qq_花开花谢_0

加入强制性data.table解决方案library(data.table) ## v 1.9.6+&nbsp;setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_")]before#&nbsp; &nbsp; attr&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type type1 type2# 1:&nbsp; &nbsp; 1&nbsp; &nbsp;foo_and_bar&nbsp; &nbsp;foo&nbsp; &nbsp;bar# 2:&nbsp; &nbsp;30 foo_and_bar_2&nbsp; &nbsp;foo bar_2# 3:&nbsp; &nbsp; 4&nbsp; &nbsp;foo_and_bar&nbsp; &nbsp;foo&nbsp; &nbsp;bar# 4:&nbsp; &nbsp; 6 foo_and_bar_2&nbsp; &nbsp;foo bar_2我们也可以通过添加和参数来确保生成的列具有正确的类型并提高性能(因为它不是真正的正则表达式)type.convertfixed"_and_"setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_", type.convert = TRUE, fixed = TRUE)]
打开App,查看更多内容
随时随地看视频慕课网APP