简体   繁体   中英

R: Splitting one column (different lengths) into new columns

I have a column of data that I would like to separate by comma (I have no problem with this part). The problem I'm having is that I would like it to be separated into new columns in the data frame, and the original column itself has different numbers of values separated by commas. For example:

Column 1

        Column1
1 AAA, BBB, CCC
2        AA232B
3  A, B, C, DDD
4     52 AJD 23

Given this set of data, I would have four columns:

  Col1       Col2       Col3       Col4
1 AAA        BBB        CCC
2 AA232B 
3 A          B          C          D
4 52 ADJ 23

Thanks!

Here is another option using cSplit

library(splitstackshape)
cSplit(df, "x", ",")
#         x_1 x_2 x_3 x_4
#1:       AAA BBB CCC  NA
#2:    AA232B  NA  NA  NA
#3:         A   B   C DDD
#4: 52 AJD 23  NA  NA  NA

###data

df <- data.frame(x=c("AAA, BBB, CCC","AA232B","A, B, C, DDD","52 AJD 23"))

Use tidyr library.

library(tidyr)

> df <- data.frame(col1 = c('AAA, BBB, CCC', 
                          'AA232B', 
                          'A, B, C, DDD', 
                          '52 AJD 23'))

> df %>% separate(col1, paste0('col', c(1:4)), sep = ',', remove = T)

> df 

##        col1 col2 col3 col4
## 1       AAA  BBB  CCC <NA>
## 2    AA232B <NA> <NA> <NA>
## 3         A    B    C  DDD
## 4 52 AJD 23 <NA> <NA> <NA>

Hope below query works, where a,b,c,d refers to column names.You can replace NA according to your wish.

df<-data.table(x=c("AAA, BBB, CCC","AA232B","A, B, C, DDD","52 AJD 23"))

df %>% separate(x, c("a","b","c","d"), extra = "merge", fill = "left")

 abcd 1 AAA BBB CCC <NA> 2 AA232B <NA> <NA> <NA> 3 ABC DDD 4 52 AJD 23 <NA>

Just for comparison, a way with only base functions, aka the case for tidyr

test <- apply(df, 1, function(i) {unlist( strsplit( i, split = ",") )})
test <- lapply(test, function(i) {c( i, rep( NA, 4-length(i)) )})
test <- data.frame(matrix(unlist(test), ncol = 4, byrow = T))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM