我想取表格的数据

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(),得到如下内容:

  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] "foo" "bar"

[[2]]
[1] "foo"   "bar_2"

[[3]]
[1] "foo" "bar"

[[4]]
[1] "foo"   "bar_2"

谢谢你的指点。我还没完全弄懂R列表。


当前回答

还有另一种方法:使用rbind on out:

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))  
out <- strsplit(as.character(before$type),'_and_') 
do.call(rbind, out)

     [,1]  [,2]   
[1,] "foo" "bar"  
[2,] "foo" "bar_2"
[3,] "foo" "bar"  
[4,] "foo" "bar_2"

并结合:

data.frame(before$attr, do.call(rbind, out))

其他回答

下面是一个与aniko的解决方案相同的一行,但使用hadley的stringr包:

do.call(rbind, str_split(before$type, '_and_'))

一个简单的方法是使用sapply()和[函数:

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
out <- strsplit(as.character(before$type),'_and_')

例如:

> data.frame(t(sapply(out, `[`)))
   X1    X2
1 foo   bar
2 foo bar_2
3 foo   bar
4 foo bar_2

Sapply()的结果是一个矩阵,需要转置并转换回数据帧。然后是一些简单的操作,产生你想要的结果:

after <- with(before, data.frame(attr = attr))
after <- cbind(after, data.frame(t(sapply(out, `[`))))
names(after)[2:3] <- paste("type", 1:2, sep = "_")

在这一点上,之后是你想要的

> after
  attr type_1 type_2
1    1    foo    bar
2   30    foo  bar_2
3    4    foo    bar
4    6    foo  bar_2

基本的,但可能很慢的:

n <- 1
for(i in strsplit(as.character(before$type),'_and_')){
     before[n, 'type_1'] <- i[[1]]
     before[n, 'type_2'] <- i[[2]]
     n <- n + 1
}

##   attr          type type_1 type_2
## 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

还有另一种方法:使用rbind on out:

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))  
out <- strsplit(as.character(before$type),'_and_') 
do.call(rbind, out)

     [,1]  [,2]   
[1,] "foo" "bar"  
[2,] "foo" "bar_2"
[3,] "foo" "bar"  
[4,] "foo" "bar_2"

并结合:

data.frame(before$attr, do.call(rbind, out))

令人惊讶的是,另一个tidyverse解决方案仍然缺失——您也可以使用带有正则表达式的tidyr::extract。

library(tidyr)
before <- data.frame(attr = c(1, 30, 4, 6), type = c("foo_and_bar", "foo_and_bar_2"))

## regex - getting all characters except an underscore till the first underscore, 
## inspired by Akrun https://stackoverflow.com/a/49752920/7941188 

extract(before, col = type, into = paste0("type", 1:2), regex = "(^[^_]*)_(.*)")
#>   attr type1     type2
#> 1    1   foo   and_bar
#> 2   30   foo and_bar_2
#> 3    4   foo   and_bar
#> 4    6   foo and_bar_2