R:Extracting words from one column into different columns

与世无争的帅哥 提交于 2019-12-19 09:57:41

问题


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 lgk
.
.
.

I would like those words to be in separate columns, for easier further processing. SO instead those words are in one column, how do I get them to separate columns?

Thanks for any help.


回答1:


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'




回答2:


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)


来源:https://stackoverflow.com/questions/31102922/rextracting-words-from-one-column-into-different-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!