R:具有如下格式的拆分字符串"xxx; yyy; zzz;"



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

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

但我想将它们分成三列

John  Peter  Eric
Susan Mary   Kate

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

你可以

试试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))

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

最新更新