在几列中拆分一列字符串

时间:2015-12-17 16:14:17

标签: r dataframe strsplit

我有数据框

df=data.frame(x=rnorm(8),y=runif(8),longstring=c("foo_100_Case1","foo_125_Case1","bar_100_Case1","bar_125_Case1","foo_100_Case2","foo_125_Case2","bar_100_Case2","bar_125_Case2"),stringsAsFactors = F)

我需要将最后一列拆分为三列,分隔符为“_”。我一直在做以下事情:

a=matrix(unlist(strsplit(df$longstring,"_",fixed=T)),8,3,byrow = T)
df$type=a[,1]
df$point=a[,2]
df$case=a[,3]

但我想知道是否有一种更简单的方法:strsplitunlist的组合特别笨拙,并且它不会使代码非常易读。

2 个答案:

答案 0 :(得分:7)

以下是一些可供尝试的选项:

我的“splitstackshape”软件包专为此类内容而设计......

library(splitstackshape)
cSplit(df, "longstring", "_")
#              x         y longstring_1 longstring_2 longstring_3
# 1: -1.41524742 0.2123978          foo          100        Case1
# 2: -1.09240237 0.3899935          foo          125        Case1
# 3:  0.39675025 0.2162463          bar          100        Case1
# 4: -1.14996728 0.7608128          bar          125        Case1
# 5: -0.07657172 0.6878348          foo          100        Case2
# 6:  0.29549599 0.2216566          foo          125        Case2
# 7:  1.78622612 0.1496666          bar          100        Case2
# 8: -0.11749579 0.9255409          bar          125        Case2

“data.table”套餐为我们带来了快速tstrsplit功能......

library(data.table)
as.data.table(df)[
  , paste0("V", 1:3) := tstrsplit(longstring, "_")][
    , longstring := NULL][]

如果您有时间并希望等待read.table开展工作......

cbind(df[1:2], read.table(text = df$longstring, sep = "_"))

如果您需要其他快速的东西......

library(iotools)
cbind(df[1:2], mstrsplit(df$longstring, sep = "_"))

答案 1 :(得分:4)

你可以尝试,

cbind(df[-3], data.frame(do.call('rbind', strsplit(df$longstring,'_'))))

#    x               y   X1  X2    X3
#1 -0.5522704 0.9998266 foo 100 Case1
#2  1.1907351 0.8979460 foo 125 Case1
#3  0.6005691 0.4301610 bar 100 Case1
#4 -1.0698081 0.9626781 bar 125 Case1
#5 -0.8526932 0.9634738 foo 100 Case2
#6  0.0100209 0.2968137 foo 125 Case2
#7 -1.5051358 0.7012956 bar 100 Case2
#8  1.0892584 0.4655736 bar 125 Case2

do.call函数允许您调用任何R函数,而不是逐个发送参数,您可以使用列表来保存参数。更多信息?do.calldo.call仅返回X1X2X3列,并获取您使用cbind绑定原始列的原始数据框。您已知道的strsplit会将字符串拆分为_

或者@joran提到你可以使用separate包中的tidyr

library(tidyr)
separate(df, longstring, c("X1", "X2", "X3"), sep="_")

#    x               y   X1  X2    X3
#1 -0.5522704 0.9998266 foo 100 Case1
#2  1.1907351 0.8979460 foo 125 Case1
#3  0.6005691 0.4301610 bar 100 Case1
#4 -1.0698081 0.9626781 bar 125 Case1
#5 -0.8526932 0.9634738 foo 100 Case2
#6  0.0100209 0.2968137 foo 125 Case2
#7 -1.5051358 0.7012956 bar 100 Case2
#8  1.0892584 0.4655736 bar 125 Case2