R:Extracting words from one column into different columns

后端 未结 2 351
走了就别回头了
走了就别回头了 2021-01-14 10:35

I\'ve been figuring this out for a couple of hours now. Let\'s say I have a column with 1-4 words, separated by space:

aba bkak absbs
a2aj akls bios
sad
fasa         


        
相关标签:
2条回答
  • 2021-01-14 11:12

    With the devel verison of data.table could also do

    library(data.table) # V >= 1.9.5
    setDT(df)[, tstrsplit(V1, ' ')]
    #      V1   V2    V3
    # 1:  aba bkak absbs
    # 2: a2aj akls  bios
    # 3:  sad   NA    NA
    # 4: fasa  lgk    NA
    

    Or with stringi (though you'll get a matrix back)

    library(stringi)
    stri_split_fixed(df$V1, ' ', simplify = TRUE)
    
    0 讨论(0)
  • 2021-01-14 11:27

    Try

    library(splitstackshape)
    cSplit(df1, 'V1', ' ')
    

    Or

    library(tidyr)
    separate(df1, 'V1', paste0('V', 1:4), sep= ' ', extra='drop')
    

    Or using base R

    read.table(text=df1$V1, sep=' ', fill=TRUE)
    

    NOTE: Used the column name as 'V1' and dataset as 'df1'

    0 讨论(0)
提交回复
热议问题