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

jke*_*ger 218 string split r dataframe 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
Run Code Online (Sandbox Code Playgroud)

并使用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
Run Code Online (Sandbox Code Playgroud)

我提出了一些令人难以置信的复杂问题,涉及某种形式的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"
Run Code Online (Sandbox Code Playgroud)

谢谢你的任何指示.我还没有完全理解R列表.

had*_*ley 260

使用 stringr::str_split_fixed

library(stringr)
str_split_fixed(before$type, "_and_", 2)
Run Code Online (Sandbox Code Playgroud)

  • 这对我今天的问题也很好..但它在每一行的开头加了一个'c'.知道为什么会这样吗??? `left_right < - str_split_fixed(as.character(split_df),'\">',2)` (2认同)
  • @ user3841581-我知道您的旧查询,但这在文档中已涉及-`str_split_fixed(“ aaa ... bbb”,fixed(“ ...”),2)`与`fixed()`可以正常工作“ pattern =”参数中的“匹配固定字符串”。“。”在正则表达式中表示“任何字符”。 (2认同)

had*_*ley 155

另一种选择是使用新的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
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法限制拆分的数量?假设我只想在 '_' 上拆分一次(或者使用 `str_split_fixed` 并在现有数据框中添加列)? (2认同)
  • `tidyr::separate` 已被 `tidyr::separate_wider_delim` 取代。 (2认同)

Dav*_*urg 56

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
Run Code Online (Sandbox Code Playgroud)

我们也可以通过添加和参数来确保生成的列具有正确的类型提高性能(因为它不是真正的正则表达式)type.convertfixed"_and_"

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

  • @Gecko 我不确定问题是什么。如果您只使用“strsplit”,它会创建一个每个槽中包含 2 个值的向量,因此“tstrsplit”将其转置为 2 个向量,每个向量中都有一个值。`paste0` 仅用于创建列名称,不用于值。方程的左侧是列名称,右侧是对列的拆分+转置操作。`:=` 代表“*就地分配*”,因此您在那里看不到 `&lt;-` 赋值运算符。 (3认同)

Ani*_*iko 51

另一种方法:使用rbindout:

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"
Run Code Online (Sandbox Code Playgroud)

并结合:

data.frame(before$attr, do.call(rbind, out))
Run Code Online (Sandbox Code Playgroud)

  • 较新的R版本的另一种选择是`strcapture(“(。*)_ and _(。*)”,as.character(before $ type),data.frame(type_1 =“”,type_2 =“”)))` (3认同)

42-*_*42- 36

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

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
Run Code Online (Sandbox Code Playgroud)

这是一个gsub方法:

before$type_1 <- gsub("_and_.+$", "", before$type)
before$type_2 <- gsub("^.+_and_", "", before$type)
before$type <- NULL
Run Code Online (Sandbox Code Playgroud)


Ram*_*ath 29

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

do.call(rbind, str_split(before$type, '_and_'))
Run Code Online (Sandbox Code Playgroud)

  • 这也适用于基础包中的strsplit (13认同)

A5C*_*2T1 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
Run Code Online (Sandbox Code Playgroud)


Rei*_*son 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_')
Run Code Online (Sandbox Code Playgroud)

例如:

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

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 = "_")
Run Code Online (Sandbox Code Playgroud)

在这一点上,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
Run Code Online (Sandbox Code Playgroud)


Yan*_* P. 8

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

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
Run Code Online (Sandbox Code Playgroud)

我们不能使用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)
}
Run Code Online (Sandbox Code Playgroud)

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

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>
Run Code Online (Sandbox Code Playgroud)

然后我们可以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
Run Code Online (Sandbox Code Playgroud)


lmo*_*lmo 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
Run Code Online (Sandbox Code Playgroud)

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


Swi*_*ton 6

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

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
Run Code Online (Sandbox Code Playgroud)


Ric*_*ven 5

从R版本3.4.0开始,您可以strcapture()utils软件包(基本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
Run Code Online (Sandbox Code Playgroud)


jpm*_*ris 5

基础但可能很慢:

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
Run Code Online (Sandbox Code Playgroud)