将数据帧字符串列拆分为多列 [英] Split data frame string column into multiple columns
本文介绍了将数据帧字符串列拆分为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取以下格式的数据
I'd like to take data of the form
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
并在上方的"type
"列上使用split()
来获得类似这样的信息:
and use split()
on the column "type
" from above to get something like this:
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列.
I came up with something unbelievably complex involving some form of apply
that worked, but I've since misplaced that. It seemed far too complicated to be the best way. I can use strsplit
as below, but then unclear how to get that back into 2 columns in the data frame.
> 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列表.
Thanks for any pointers. I've not quite groked R lists just yet.
推荐答案
使用stringr::str_split_fixed
library(stringr)
str_split_fixed(before$type, "_and_", 2)
这篇关于将数据帧字符串列拆分为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文