将数据帧的列拆分为多列 [英] Split a column of a data frame to 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
并使用 split()
从上面的列类型
获得这样的东西:
attr type_1 type_2
1 1 foo bar
2 30 foo bar_2
3 4 foo bar
4 6 foo bar_2
我想出了一些令人难以置信的复杂性,涉及某种形式的应用
,但是我已经错位了。看起来太复杂了,不是最好的办法。我可以使用 strsplit
如下,但是不清楚如何将它们重新放回数据框中的2列。
> strsplit(as.character(before $ type),'_ and_')
[[1]]
[1]foobar
[[2]]
[1]foobar_2
[[3]]
[1]foobar
[[4 ]]
[1]foobar_2
感谢任何指针。我还没有很清楚R列表。
解决方案
使用 stringr :: str_split_fixed
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
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
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"
Thanks for any pointers. I've not quite groked R lists just yet.
解决方案
Use stringr::str_split_fixed
library(stringr)
str_split_fixed(before$type, "_and_", 2)
这篇关于将数据帧的列拆分为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文