R 将数据框字符串列拆分为多列
我想要表格上的数据R 将数据框字符串列拆分为多列,r,string,dataframe,split,r-faq,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(),可以得到如下结果: attr type_1 type_2 1
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()
,可以得到如下结果:
attr type_1 type_2
1 1 foo bar
2 30 foo bar_2
3 4 foo bar
4 6 foo bar_2
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
我想出了一些难以置信的复杂方法,包括某种形式的apply
,但后来我把它放错了地方。这似乎太复杂了,不是最好的办法。我可以使用下面的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"
谢谢你的指点。我还没有完全研究过R列表。请注意,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
在$type_1之前一个简单的方法是使用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_')
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 = "_")
如果您想坚持使用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")
tmp另一种方法:在out
上使用rbind
:
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"
这是一个与aniko的解决方案相同的单行程序,但使用hadley的stringr包:
do.call(rbind, str_split(before$type, '_and_'))
使用stringr::str\u split\u fixed
library(stringr)
str_split_fixed(before$type, "_and_", 2)
另一个选择是使用新的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
库(dplyr)
图书馆(tidyr)
之前%
单独(类型,c(“foo”、“bar”)、“uU和uU”)
##阿特富巴酒店
##1福吧
##2 30福巴2
##3.4富吧
##4 6福巴2
要添加选项,您还可以使用mysplitstackshape::cSplit
函数,如下所示:
attr type_1 type_2
1 1 foo bar
2 30 foo bar_2
3 4 foo bar
4 6 foo bar_2
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
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
我们还可以通过添加type.convert
和fixed
参数来确保生成的列具有正确的类型并提高性能(因为“\u和\u”
实际上不是正则表达式)
下面是一个基本的R one行程序,它与以前的许多解决方案重叠,但返回一个带有专有名称的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
out自R版本3.4.0以来,您可以使用utils包(随基本R安装一起提供)中的strcapture()
,将输出绑定到其他列上
out这个问题已经很老了,但我会补充我发现的解决方案是目前最简单的
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
library(重塑2)
before=data.frame(attr=c(1,30,4,6),type=c('foo_和_-bar','foo_和_-bar_-2'))
newColNames这个主题几乎已经精疲力竭了,不过我想提供一个更一般的版本的解决方案,在这个版本中,您事先不知道输出列的数量
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
我们不能使用dplyrseparate()
,因为在拆分之前我们不知道结果列的数量,所以我创建了一个函数,该函数使用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)
}
然后我们可以使用收集来整理
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
基本但可能缓慢:
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
n这里是另一个基本的R解决方案。我们可以使用read.table
,但由于它只接受一个字节sep
参数,并且这里有多字节分隔符,我们可以使用gsub
将多字节分隔符替换为任何一个字节分隔符,并将其用作read.table
中的sep
参数
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)))
这对我今天的问题也很有效。但它在每行的开头添加了一个“c”。你知道为什么吗?left\u right我想用一个有“…”的模式分割,当我应用该函数时,它什么也不返回。可能是什么问题。我的类型类似于“test…score”@user3841581-我知道您的旧查询,但文档中包含了这一点-str_split_fixed(“aaa…bbb”,fixed(“…”),2)
与fixed()
配合使用可以“匹配固定字符串”在pattern=
参数中。
在正则表达式中表示“任意字符”。感谢hadley,这是一种非常方便的方法,但有一点可以改进,如果原始列中存在NA,在分离后,它将成为结果列中的七个空字符串,这是不需要的,我希望在分离后保持NA仍然是NAell,即,如果缺少分隔符!即,如果我有一个向量“aIs”,有没有办法用分隔符限制拆分的数量?假设我只想在“u”上拆分一次(或者用str\u split\u fixed
并将列添加到现有数据帧中)?很好的捕获,对我来说是最好的解决方案。虽然比使用stringr
软件包慢了一点。这个函数是否被重命名为strsplit()
?在较新的R版本上,另一个替代方法是strcapture((.*)和(.*),as.character(在$type之前),data.frame(type_1=“”,type_2=“”)
3年后-此选项对我遇到的类似问题最有效-但是我正在使用的数据帧有54列,我需要将它们全部拆分为两列。除了将上述命令键入54次之外,还有什么方法可以做到这一点吗?非常感谢,Nicki。@Nicki,您是否尝试过提供n列的向量ames还是列位置?这应该可以做到…这不仅仅是重命名列-我需要按照上面的方式拆分列,有效地将我的df中的列数增加一倍。下面是我最后使用的:df2如果您的'\u和
模式的数目不同,您可以找到最大匹配数(即未来的列)使用max(长度(strsplit(在$type、'.'和''.'之前))
这是我最喜欢的答案,效果非常好!请解释一下它是如何工作的。为什么转置(strsplit(…)而不是粘贴0来连接字符串
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>
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
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
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
cbind(before[1], read.table(text = gsub('_and_', ' ', before$type),
col.names = paste0("type_", 1:2)))