R:分割字符串,其格式类似于“xxx; yyy; zzz;”

时间:2015-03-15 01:47:07

标签: r string-split

我得到的原始数据是这样的,它们都在一栏

John;Peter;Eric;
Susan;Mary;Kate;

但我想将它们分成三个单独的列

John  Peter  Eric
Susan Mary   Kate

有谁能告诉我如何在R中做到这一点?提前谢谢!

3 个答案:

答案 0 :(得分:4)

您可以尝试cSplit

library(splitstackshape)
cSplit(df1, 'col1', ';')
#    col1_1 col1_2 col1_3
#1:   John  Peter   Eric
#2:  Susan   Mary   Kate

library(tidyr)
separate(df1, col1, into=paste0('col', 1:4), ';')[-4]
#    col1  col2 col3
#1  John Peter Eric
#2 Susan  Mary Kate

或者

 extract(df1, col1, into=paste0('col', 1:3), '([^;]+);([^;]+);([^;]+)')
 #   col1  col2 col3
 #1  John Peter Eric
 #2 Susan  Mary Kate

或使用base R

 as.data.frame(do.call(rbind,strsplit(df1$col1, ';')))

数据

df1 <- structure(list(col1 = c("John;Peter;Eric;", "Susan;Mary;Kate;"
 )), .Names = "col1", class = "data.frame", row.names = c(NA, -2L))

答案 1 :(得分:3)

fread()添加到批次

x <- "John;Peter;Eric;
Susan;Mary;Kate;"

data.table::fread(x, header = FALSE, drop = 4)
#       V1    V2   V3
# 1:  John Peter Eric
# 2: Susan  Mary Kate

直接返回数据框,

data.table::fread(x, header = FALSE, drop = 4, data.table = FALSE)
#      V1    V2   V3
# 1  John Peter Eric
# 2 Susan  Mary Kate

对于可以转换为数据框的快速矩阵,

library(stringi)
stri_split_fixed(stri_split_lines1(x), ";", omit = TRUE, simplify = TRUE)
#      [,1]    [,2]    [,3]  
# [1,] "John"  "Peter" "Eric"
# [2,] "Susan" "Mary"  "Kate"

答案 2 :(得分:1)

base R: 

  matrix(regmatches(x,gregexpr("([aA-zZ]+)",x,perl=TRUE))[[1]],ncol=3,byrow=T)
     [,1]    [,2]    [,3]  
[1,] "John"  "Peter" "Eric"
[2,] "Susan" "Mary"  "Kate"