我有一个R dataFrame包含以下内容:
column1 column2
score1...test1 10
score2...test2 11
score3...test3 15
我想将我的dataFrame重塑为以下内容:
column1 column2 score test
score1...test1 10 score1 test1
score1...test2 11 score2 test2
score1...test3 15 score3 test3
我尝试使用
library(stringr)
temp=str_split_fixed(df, " ...", 4)
但我得到这个
[,1] [,2] [,3] [,4]
如何解决这个问题?
我们可以通过做到这一点base R
。更换...
与,
使用sub
,读取与字符串read.csv
创建一个data.frame有两列,cbind
与原来的数据集,以获得预期的输出。
cbind(df,read.csv(text=sub('[[:punct:]]+', ',',
df$column1), header=FALSE, col.names=c('score', 'test')))
# column1 column2 score test
#1 score1...test1 10 score1 test1
#2 score2...test2 11 score2 test2
#3 score3...test3 15 score3 test3
或者我们可以直接将其...
用作模式sub
,替换为“,”,其余在上面。
cbind(df,read.csv(text=sub('...', ',',
df$column1, fixed=TRUE), header=FALSE,
col.names=c('score', 'test')))
如果我们需要一个一揽子解决方案,separate
从tidyr
可以使用。
library(tidyr)
separate(df, column1, into=c("score", "test"), remove=FALSE)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句