Reputation: 161
I have a string vector in R like this c('a,b,c,d','c,d,e','d,c','a,b,d') I have to convert it to a Data frame as given below. Note that strings could be off different lengths. So here in 3rd row after d & c there should be blanks under columns 3 & 4
a b c d
c d e
d c
a b d
Upvotes: 0
Views: 1034
Reputation: 886948
We split by the ,
into a list
, append NA
at the end for those having less elements and convert to data.frame
lst <- strsplit(v1, ",")
out <- do.call(rbind.data.frame, lapply(lst, `length<-`, max(lengths(lst))))
colnames(out) <- paste0("V", seq_along(out))
out <- sapply(out, as.character)
out[is.na(out)] <- ""
out
Upvotes: 3
Reputation: 269461
Using the test input in the Note at the end.
read.table(text = x, sep = ",", fill = TRUE, as.is = TRUE)
giving:
V1 V2 V3 V4
1 a b c d
2 c d e
3 d c
4 a b d
Test input
x <- c('a,b,c,d','c,d,e','d,c','a,b,d')
Upvotes: 3
Reputation: 2133
Its pretty simple. use below
test <- c('a,b,c,d','c,d,e','d,c','a,b,d')
data_frame <- data.frame(test)
data_frame
Upvotes: 0