将数据框字符串列拆分为多列 [英] Split data frame string column into multiple columns
本文介绍了将数据框字符串列拆分为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取表单的数据
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屋!
查看全文