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

Split data frame string column into multiple columns

提问人:jkebinger 提问时间:12/4/2010 最后编辑:David Arenburgjkebinger 更新时间:9/28/2023 访问量:589579

问:

我想获取表格的数据

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

我想出了一些令人难以置信的复杂的东西,涉及某种形式的工作,但后来我把它放错了地方。这似乎太复杂了,不是最好的方法。我可以按如下方式使用,但随后不清楚如何将其恢复到数据框中的 2 列中。applystrsplit

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

字符串 数据帧 拆分 R-FAQ

评论


答:

46赞 IRTFM 12/4/2010 #1

请注意,带有“[”的 sapply 可用于提取这些列表中的第一项或第二项,以便:

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
18赞 Gavin Simpson 12/4/2010 #2

一个简单的方法是使用和功能: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
4赞 ashaw 12/4/2010 #3

如果您想坚持使用另一种方法是使用该命令。这是沿着这些思路的解决方案。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")
74赞 Aniko 12/4/2010 #4

另一种方法:用于: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"

并结合:

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

评论

8赞 alexis_laz 11/11/2016
较新的 R 版本上的另一种选择是strcapture("(.*)_and_(.*)", as.character(before$type), data.frame(type_1 = "", type_2 = ""))
1赞 Cole 4/4/2023
这是正确的解决方案。简单,不需要第三方包。
35赞 Ramnath 12/4/2010 #5

这是一个与 Aniko 的解决方案相同的衬里,但使用了 Hadley 的纵梁包:

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

评论

1赞 Melka 3/30/2016
好渔获,对我来说最好的解决方案。虽然比包装慢一点。stringr
0赞 user5359531 2/12/2021
这个函数是否重命名为?strsplit()
355赞 hadley 12/4/2010 #6

stringr::str_split_fixed

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

评论

4赞 LearneR 7/28/2015
这对我今天的问题也很好。但它在每行的开头添加了一个“C”。知道这是为什么吗???left_right <- str_split_fixed(as.character(split_df),'\">',2)
0赞 user3841581 3/14/2016
我想用一个带有“...”的模式进行拆分,当我应用该函数时,它什么也没返回。可能是什么问题。我的类型类似于“测试......得分”
6赞 thelatemail 8/9/2017
@user3841581 - 我知道您的旧查询,但这在文档中有所介绍 - 适用于参数中的“匹配固定字符串”。 表示正则表达式中的“任何字符”。str_split_fixed("aaa...bbb", fixed("..."), 2)fixed()pattern=.
0赞 cloudscomputes 9/15/2017
谢谢哈德利,非常方便的方法,但有一件事可以改进,如果原始列中有 NA,分离后它会在结果列中变成 sevaral 空字符串,这是不需要的,我想在分离后保持 NA 仍然是 NA
0赞 maycca 5/23/2018
效果很好,即如果缺少分隔符!即,如果我有一个向量 'a<-c(“1N”, “2N”)',我想在列 '1,1, “N”, “N”' 中分隔,我运行 'str_split_fixed(s, “”, 2)'。我只是不确定如何在这种方法中命名我的新列,'col1<-c(1,1)' 和 'col2<-c(“N”, “N”)'
270赞 hadley 6/12/2014 #7

您可以使用该包。tidyr

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

library(tidyr)
before |>
  separate_wider_delim(type, delim = "_and_", names = c("foo", "bar"))
# # A tibble: 4 × 3
#    attr foo   bar  
#   <dbl> <chr> <chr>
# 1     1 foo   bar  
# 2    30 foo   bar_2
# 3     4 foo   bar  
# 4     6 foo   bar_2

(或使用旧版本的tidyr)

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

评论

4赞 JelenaČuklina 1/11/2016
有没有办法限制拆分的数量?假设我只想在“_”上拆分一次(或者使用并向现有数据帧添加列)?str_split_fixed
0赞 Prradep 11/8/2021
@hadley 如果我想根据秒进行拆分怎么样?我想要值为 , /?_foo_andbarbar_2
2赞 robertspierre 7/12/2023
tidyr::separate已被 取代。tidyr::separate_wider_delim
31赞 A5C1D2H2I1M1N2O1R2T1 9/27/2014 #8

要添加到选项中,您还可以像这样使用我的函数: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

评论

1赞 Nicki 8/3/2017
3 年后 - 此选项最适合解决我遇到的类似问题 - 但是我正在使用的数据帧有 54 列,我需要将它们全部分成两列。有没有办法使用这种方法做到这一点 - 除了键入上述命令 54 次之外?非常感谢,妮琪。
0赞 A5C1D2H2I1M1N2O1R2T1 8/5/2017
@Nicki,您是否尝试过提供列名或列位置的向量?那应该可以做到......
0赞 Nicki 8/7/2017
这不仅仅是重命名列 - 我需要像上面一样从字面上拆分列,有效地将我的 df 中的列数增加一倍。以下是我最后使用的: df2 <- cSplit(df1, splitCols = 1:54, “/”)
94赞 David Arenburg 10/14/2015 #9

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_"

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

评论

1赞 andschar 6/4/2019
如果您的模式数量不同,您可以找出最大匹配数(即未来列)'_and_'max(lengths(strsplit(before$type, '_and_')))
0赞 Gecko 5/14/2020
这是我最喜欢的答案,效果很好!您能否解释一下它是如何工作的。为什么 transpose(strsplit(...)) 并且不是用于连接字符串的 paste0 - 而不是拆分它们......
3赞 David Arenburg 5/14/2020
@Gecko我不确定问题是什么。如果您只使用它,则会创建一个在每个插槽中具有 2 个值的向量,因此将其转置为 2 个向量,每个向量中都有一个值。 仅用于创建列名,不用于值。在等式的 LHS 上是列名,在 RHS 上是列上的拆分 + 转置操作。 代表“就地分配”,因此您在那里看不到分配运算符。strsplittstrsplitpaste0:=<-
9赞 lmo 7/23/2016 #10

下面是一个基本的 R 单行,它与以前的许多解决方案重叠,但返回一个具有正确名称的 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

它用于分解变量,并使用 / 将数据放回 data.frame。额外的增量改进是使用 将变量名称添加到 data.frame。strsplitdata.framedo.callrbindsetNames

11赞 Rich Scriven 8/29/2017 #11

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

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

评论

1赞 Chris 12/24/2022
这是最连贯的“为目的而建”。
8赞 Swifty McSwifterton 9/29/2017 #12

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

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

评论

0赞 Apricot 6/17/2019
在管理 df 向量时,这是迄今为止最简单的
30赞 Yannis P. 11/2/2017 #13

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

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

评论

1赞 MEC 2/22/2023
这非常有用。多年后,我想知道是否有可能引入可以插入 for 循环的 colnames。例如,我想split_into_multiple 10 列(或更多),但我不想一次将它们拆分为每列。我希望生成的拆分列绑定在一起。我找不到以编程方式选择列名的方法(它给了我错误)选项!as.name() 说没有这样的属性......你会怎么做?
0赞 Yannis P. 3/19/2023
我很高兴你仍然觉得它很有用@MEC。我的 R 知识已经抛弃了我,不知道如何用这部分暗示你。我认为 Python 可能会提供一些东西,但需要一些功课......pandas
7赞 jpmorris 2/17/2018 #14

基本但可能很慢:

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
1赞 Ronak Shah 1/4/2020 #15

这是另一个基本 R 解决方案。我们可以使用 但是,因为它只接受一个字节的参数,而这里我们有多字节分隔符,我们可以用来将多字节分隔符替换为任何单字节分隔符,并将其用作参数read.tablesepgsubsepread.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)))
1赞 tjebo 2/10/2022 #16

令人惊讶的是,仍然缺少另一个整洁的解决方案 - 您也可以使用带有正则表达式的 。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
0赞 Alan Gómez 7/14/2023 #17

另一个基本 R 解决方案也是将一列拆分为几列的通用方法:

数据

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

程序

attach(before)
before$type2 <- gsub("(\\w*)_and_(\\w*)", "c('\\1', '\\2')", type)
#this recode the column type to c("blah", "blah") form

cbind(before,t(sapply(1:nrow(before), function(x) eval(parse(text=before$type2[x])))))
#this split the desired column into several ones named 1 2 3 and so on

输出

  attr          type             type2   1     2
1    1   foo_and_bar   c('foo', 'bar') foo   bar
2   30 foo_and_bar_2 c('foo', 'bar_2') foo bar_2
3    4   foo_and_bar   c('foo', 'bar') foo   bar
4    6 foo_and_bar_2 c('foo', 'bar_2') foo bar_2
1赞 Mark 7/21/2023 #18

自从提出这个问题以来,已被 separate_longer_* 和 separate_wider_* 函数所取代。separate

现在的方法是:

library(tidyr)
separate_wider_delim(before, type, delim = "_and_", names_sep = "_")

你也可以使用 ,但我会把它留给读者作为练习:-)separate_wider_regex