将数据帧字符串列分割为多个列

时间:2021-12-04 19:36:05

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:

然后在上面的“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

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,但是不清楚如何将它恢复为数据框中的两列。

> 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.

感谢任何指针。我还没有摸索过R列表。

15 个解决方案

#1


193  

Use stringr::str_split_fixed

使用stringr::str_split_fixed

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

#2


112  

Another option is to use the new tidyr package.

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

#3


43  

5 years later adding the obligatory data.table solution

5年后加入义务数据。表解决方案

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)

我们还可以通过添加type来确保结果列具有正确的类型并提高性能。转换和固定的参数(因为“_and_”并不是真正的regex)

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

#4


40  

Yet another approach: use rbind on out:

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

And to combine:

并结合:

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

#5


30  

Notice that sapply with "[" can be used to extract either the first or second items in those lists so:

注意,sapply with "["可用于提取这些列表中的第一或第二项,因此:

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

And here's a gsub method:

这里有一个gsub方法:

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

#6


26  

here is a one liner along the same lines as aniko's solution, but using hadley's stringr package:

这里有一个与aniko的解决方案类似的内线,但是使用hadley的stringr包:

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

#7


16  

To add to the options, you could also use my splitstackshape::cSplit function like this:

要添加到选项中,您还可以使用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

#8


12  

An easy way is to use sapply() and the [ function:

一个简单的方法是使用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_')

For example:

例如:

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

sapply()'s result is a matrix and needs transposing and casting back to a data frame. It is then some simple manipulations that yield the result you wanted:

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

At this point, after is what you wanted

此时,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

#9


7  

Here is a base R one liner that overlaps a number of previous solutions, but returns a data.frame with the proper names.

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

It uses strsplit to break up the variable, and data.frame with do.call/rbind to put the data back into a data.frame. The additional incremental improvement is the use of setNames to add variable names to the data.frame.

它使用strsplit来分解变量,并使用do来分割data.frame。调用/rbind将数据放回到data.frame中。附加的增量改进是使用setNames向data.frame添加变量名。

#10


4  

Another approach if you want to stick with strsplit() is to use the unlist() command. Here's a solution along those lines.

如果要使用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  

Since R version 3.4.0 you can use strcapture() from the utils package (included with base R installs), binding the output onto the other column(s).

因为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  

The subject is almost exhausted, I 'd like though to offer a solution to a slightly more general version where you don't know the number of output columns, a priori. So for example you have

这个主题几乎已经耗尽了,我想提供一个解决方案给稍微更一般的版本,您不知道输出列的数量,这是先验的。举个例子

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

We can't use dplyr separate() because we don't know the number of the result columns before the split, so I have then created a function that uses stringr to split a column, given the pattern and a name prefix for the generated columns. I hope the coding patterns used, are correct.

我们不能使用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)
}

We can then use split_into_multiple in a dplyr pipe as follows:

然后我们可以在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>

And then we can use gather to tidy up...

然后我们可以用集合来整理……

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

#13


3  

This question is pretty old but I'll add the solution I found the be the simplest at present.

这个问题很老了,但我要补充我目前找到的最简单的解决方案。

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

#14


3  

base but probably slow:

基础但可能缓慢:

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

#15


-4  

tp <- c("a-c","d-e-f","g-h-i","m-n")

temp = strsplit(as.character(tp),'-')

x=c();
y=c();
z=c();

#tab=data.frame()
#tab= cbind(tab,c(x,y,z))

for(i in 1:length(temp) )
{
  l = length(temp[[i]]);

  if(l==2)
  {
     x=c(x,temp[[i]][1]);
     y=c(y,"NA")
     z=c(z,temp[[i]][2]);

    df= as.data.frame(cbind(x,y,z)) 

  }else
  {
    x=c(x,temp[[i]][1]);
    y=c(y,temp[[i]][2]);
    z=c(z,temp[[i]][3]);

    df= as.data.frame(cbind(x,y,z))
   }
}

#1


193  

Use stringr::str_split_fixed

使用stringr::str_split_fixed

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

#2


112  

Another option is to use the new tidyr package.

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

#3


43  

5 years later adding the obligatory data.table solution

5年后加入义务数据。表解决方案

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)

我们还可以通过添加type来确保结果列具有正确的类型并提高性能。转换和固定的参数(因为“_and_”并不是真正的regex)

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

#4


40  

Yet another approach: use rbind on out:

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

And to combine:

并结合:

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

#5


30  

Notice that sapply with "[" can be used to extract either the first or second items in those lists so:

注意,sapply with "["可用于提取这些列表中的第一或第二项,因此:

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

And here's a gsub method:

这里有一个gsub方法:

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

#6


26  

here is a one liner along the same lines as aniko's solution, but using hadley's stringr package:

这里有一个与aniko的解决方案类似的内线,但是使用hadley的stringr包:

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

#7


16  

To add to the options, you could also use my splitstackshape::cSplit function like this:

要添加到选项中,您还可以使用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

#8


12  

An easy way is to use sapply() and the [ function:

一个简单的方法是使用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_')

For example:

例如:

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

sapply()'s result is a matrix and needs transposing and casting back to a data frame. It is then some simple manipulations that yield the result you wanted:

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

At this point, after is what you wanted

此时,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

#9


7  

Here is a base R one liner that overlaps a number of previous solutions, but returns a data.frame with the proper names.

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

It uses strsplit to break up the variable, and data.frame with do.call/rbind to put the data back into a data.frame. The additional incremental improvement is the use of setNames to add variable names to the data.frame.

它使用strsplit来分解变量,并使用do来分割data.frame。调用/rbind将数据放回到data.frame中。附加的增量改进是使用setNames向data.frame添加变量名。

#10


4  

Another approach if you want to stick with strsplit() is to use the unlist() command. Here's a solution along those lines.

如果要使用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  

Since R version 3.4.0 you can use strcapture() from the utils package (included with base R installs), binding the output onto the other column(s).

因为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  

The subject is almost exhausted, I 'd like though to offer a solution to a slightly more general version where you don't know the number of output columns, a priori. So for example you have

这个主题几乎已经耗尽了,我想提供一个解决方案给稍微更一般的版本,您不知道输出列的数量,这是先验的。举个例子

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

We can't use dplyr separate() because we don't know the number of the result columns before the split, so I have then created a function that uses stringr to split a column, given the pattern and a name prefix for the generated columns. I hope the coding patterns used, are correct.

我们不能使用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)
}

We can then use split_into_multiple in a dplyr pipe as follows:

然后我们可以在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>

And then we can use gather to tidy up...

然后我们可以用集合来整理……

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

#13


3  

This question is pretty old but I'll add the solution I found the be the simplest at present.

这个问题很老了,但我要补充我目前找到的最简单的解决方案。

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

#14


3  

base but probably slow:

基础但可能缓慢:

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

#15


-4  

tp <- c("a-c","d-e-f","g-h-i","m-n")

temp = strsplit(as.character(tp),'-')

x=c();
y=c();
z=c();

#tab=data.frame()
#tab= cbind(tab,c(x,y,z))

for(i in 1:length(temp) )
{
  l = length(temp[[i]]);

  if(l==2)
  {
     x=c(x,temp[[i]][1]);
     y=c(y,"NA")
     z=c(z,temp[[i]][2]);

    df= as.data.frame(cbind(x,y,z)) 

  }else
  {
    x=c(x,temp[[i]][1]);
    y=c(y,temp[[i]][2]);
    z=c(z,temp[[i]][3]);

    df= as.data.frame(cbind(x,y,z))
   }
}