Split a column of a data frame to 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
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.
使用stringr::str_split_fixed
library(stringr)
str_split_fixed(before$type, "_and_", 2)
另一种选择是使用新的tidyr软件包。
library(dplyr)
library(tidyr)
before <- data.frame(
attr = c(1, 30 ,4 ,6 ),
type = c('foo_and_bar', 'foo_and_bar_2')
)
before %>%
separate(type, c("foo", "bar"), "_and_")
## attr foo bar
## 1 1 foo bar
## 2 30 foo bar_2
## 3 4 foo bar
## 4 6 foo bar_2
5 years later adding the obligatory data.table
solution
library(data.table) ## v 1.9.6+
setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_")]
before
# attr type type1 type2
# 1: 1 foo_and_bar foo bar
# 2: 30 foo_and_bar_2 foo bar_2
# 3: 4 foo_and_bar foo bar
# 4: 6 foo_and_bar_2 foo bar_2
We could also both make sure that the resulting columns will have correct types and improve performance by adding type.convert
and fixed
arguments (since "_and_"
isn't really a regex)
setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_", type.convert = TRUE, fixed = TRUE)]
链接地址: http://www.djcxy.com/p/70906.html
上一篇: 如何在数据框中按名称删除列
下一篇: 将数据框的列拆分为多个列