将数据框架字符串列拆分为多个列

时间:2010-12-03 22:29:15

标签: r string dataframe split r-faq

我想获取表格

的数据
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()”列中使用type来获取类似内容:

  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列。

> 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列表。

15 个答案:

答案 0 :(得分:240)

使用stringr::str_split_fixed

library(stringr)
str_split_fixed(before$type, "_and_", 2)

答案 1 :(得分:148)

另一种选择是使用新的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

答案 2 :(得分:51)

5年后添加强制性data.table解决方案

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

我们还可以通过添加type.convertfixed参数来确保生成的列具有正确的类型以提高性能(因为"_and_" isn&# 39;真的是一个正则表达式)

setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_", type.convert = TRUE, fixed = TRUE)]

答案 3 :(得分:48)

另一种方法:在rbind上使用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))

答案 4 :(得分:34)

请注意,使用“[”可以用来提取这些列表中的第一个或第二个项目,所以:

before$type_1 <- sapply(strsplit(as.character(before$type),'_and_'), "[", 1)
before$type_2 <- sapply(strsplit(as.character(before$type),'_and_'), "[", 2)
before$type <- NULL

这是一个gsub方法:

before$type_1 <- gsub("_and_.+$", "", before$type)
before$type_2 <- gsub("^.+_and_", "", before$type)
before$type <- NULL

答案 5 :(得分:27)

这是一个与aniko的解决方案相同的线条,但是使用了hadley的stringr包:

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

答案 6 :(得分:19)

要添加选项,您还可以使用我的splitstackshape::cSplit功能:

library(splitstackshape)
cSplit(before, "type", "_and_")
#    attr type_1 type_2
# 1:    1    foo    bar
# 2:   30    foo  bar_2
# 3:    4    foo    bar
# 4:    6    foo  bar_2

答案 7 :(得分:13)

一种简单的方法是使用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就是您想要的

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

答案 8 :(得分:7)

这是一个基本的R one liner,它与许多以前的解决方案重叠,但返回一个带有正确名称的data.frame。

out <- setNames(data.frame(before$attr,
                  do.call(rbind, strsplit(as.character(before$type),
                                          split="_and_"))),
                  c("attr", paste0("type_", 1:2)))
out
  attr type_1 type_2
1    1    foo    bar
2   30    foo  bar_2
3    4    foo    bar
4    6    foo  bar_2

它使用strsplit来分解变量,data.frame使用do.call / rbind将数据放回data.frame。额外的增量改进是使用setNames将变量名称添加到data.frame。

答案 9 :(得分:6)

主题几乎已经筋疲力尽了,我想提供一个稍微更通用的版本的解决方案,你不知道输出列的数量,先验。所以例如你有

before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2', 'foo_and_bar_2_and_bar_3', 'foo_and_bar'))
  attr                    type
1    1             foo_and_bar
2   30           foo_and_bar_2
3    4 foo_and_bar_2_and_bar_3
4    6             foo_and_bar

我们无法使用dplyr separate()因为我们在分割之前不知道结果列的数量,所以我创建了一个使用stringr分割的函数给定生成列的模式和名称前缀的列。我希望使用的编码模式是正确的。

split_into_multiple <- function(column, pattern = ", ", into_prefix){
  cols <- str_split_fixed(column, pattern, n = Inf)
  # Sub out the ""'s returned by filling the matrix to the right, with NAs which are useful
  cols[which(cols == "")] <- NA
  cols <- as.tibble(cols)
  # name the 'cols' tibble as 'into_prefix_1', 'into_prefix_2', ..., 'into_prefix_m' 
  # where m = # columns of 'cols'
  m <- dim(cols)[2]

  names(cols) <- paste(into_prefix, 1:m, sep = "_")
  return(cols)
}

然后我们可以在dplyr管道中使用split_into_multiple,如下所示:

after <- before %>% 
  bind_cols(split_into_multiple(.$type, "_and_", "type")) %>% 
  # selecting those that start with 'type_' will remove the original 'type' column
  select(attr, starts_with("type_"))

>after
  attr type_1 type_2 type_3
1    1    foo    bar   <NA>
2   30    foo  bar_2   <NA>
3    4    foo  bar_2  bar_3
4    6    foo    bar   <NA>

然后我们可以使用gather来整理......

after %>% 
  gather(key, val, -attr, na.rm = T)

   attr    key   val
1     1 type_1   foo
2    30 type_1   foo
3     4 type_1   foo
4     6 type_1   foo
5     1 type_2   bar
6    30 type_2 bar_2
7     4 type_2 bar_2
8     6 type_2   bar
11    4 type_3 bar_3

答案 10 :(得分:4)

如果您想坚持strsplit(),另一种方法是使用unlist()命令。以下是这些方面的解决方案。

tmp <- matrix(unlist(strsplit(as.character(before$type), '_and_')), ncol=2,
   byrow=TRUE)
after <- cbind(before$attr, as.data.frame(tmp))
names(after) <- c("attr", "type_1", "type_2")

答案 11 :(得分:4)

从R 3.4.0版开始,您可以使用 utils 包中的strcapture()(包含在基本R安装中),将输出绑定到其他列上。

out <- strcapture(
    "(.*)_and_(.*)",
    as.character(before$type),
    data.frame(type_1 = character(), type_2 = character())
)

cbind(before["attr"], out)
#   attr type_1 type_2
# 1    1    foo    bar
# 2   30    foo  bar_2
# 3    4    foo    bar
# 4    6    foo  bar_2

答案 12 :(得分:4)

这个问题已经很老了,但我会添加我发现目前最简单的解决方案。

library(reshape2)
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
newColNames <- c("type1", "type2")
newCols <- colsplit(before$type, "_and_", newColNames)
after <- cbind(before, newCols)
after$type <- NULL
after

答案 13 :(得分:4)

基础但可能很慢:

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

答案 14 :(得分:1)

这是另一个基本的R解决方案。我们可以使用read.table,但是由于它只接受一个字节的sep参数,并且这里有多字节分隔符,因此可以使用gsub将多字节分隔符替换为任何一个字节分隔符,然后将其用作sep

中的read.table自变量
cbind(before[1], read.table(text = gsub('_and_', '\t', before$type), 
                 sep = "\t", col.names = paste0("type_", 1:2)))

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

在这种情况下,我们也可以通过将其替换为默认的sep参数来使其更短,因此我们不必明确提及它

cbind(before[1], read.table(text = gsub('_and_', ' ', before$type), 
                 col.names = paste0("type_", 1:2)))
相关问题