Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

r- split a column to multiple columns - changing pattern

Please note I read a similar question about splitting a column of a data frame to multiple columns, but my case is different.

My form of data is as follows:

  name    description      
1 a       hello|hello again|something 
2 b       hello again|something|hello
3 c       hello again|hello
4 d

I'd like to split the description column as follows:

  name    description_1 description_2 description_3
1 a       hello         hello again   something 
2 b       hello         hello again   something 
3 c       hello         hello again   N/A
4 d       N/A           N/A           N/A

Any suggestions, directions?

EDIT: Following @akrun and @Sotos answers (thanks!), here's a more accurate presentation of my data:

  name    description      
1 a       add words|change|approximate 
2 b       control|access|approximate
4 d

therefore, sorting the data alphabetically results in:

  name    description_1    description_2 description_3
1 a       add words        approximate   change 
2 b       access           approximate   control 
4 d       N/A           N/A           N/A

while, what I need is:

  name    desc_1      desc_2       desc_3   desc_4   desc_5
1 a       add words   approximate  change   N/A      N/A
2 b       N/A         approximate  N/A      control  access 
4 d       N/A         N/A          N/A      N/A      N/A

I don't mind how description is sorted (if at all), as long as at each column (desc_1..5) I will have the same description. Hopefully, that clarifies my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can use match to change the order based on the order of the first entry of description, and then split using cSplit from splitstackshape package,

library(splitstackshape)
#make sure column 'description' is a character
df$description <- as.character(df$description)

ind <- strsplit(df$description, '\|')[[1]]
df$description <- sapply(strsplit(df$description, '\|'), function(i) 
                                         paste(i[order(match(i, ind))], collapse = '|'))

cSplit(df, 'description', sep = '|', 'wide')
#   name description_1 description_2 description_3
#1:    a         hello   hello_again     something
#2:    b         hello   hello_again     something
#3:    c         hello   hello_again            NA
#4:    d            NA            NA            NA

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...