Reputation: 13319
I'm trying to use lapply
and do.call
to combine lists into a data.frame
object. However, how do I get to prevent factor conversion to levels within the resulting object?
Illustration:
dummy<-list(list(data.frame(A=c("Boy","He","Is","Cool"),
stringsAsFactors = T)),
list(data.frame(B=c("Boy","Not","So","Cool"),
stringsAsFactors = T)))
test1<-lapply(dummy,"[")
as.data.frame(do.call(cbind,test1))
Issue:
V1 V2
1 1, 3, 4, 2 1, 3, 4, 2
Ignoring the nature of the output, how can I keep the original "values" ie Boy,cool,etc? Thanks! Desired Output:
A B
contents contents
I cannot know the number of lists beforehand. I've tried this but it returns NAs:
plyr::ldply(test1,function(ele) do.call(cbind,ele))
Upvotes: 0
Views: 63
Reputation: 10223
Absolutely no conversion has been done:
out <- as.data.frame(do.call(cbind,test1))
out[[1]]
#[[1]]
# A
#1 Boy
#2 He
#3 Is
#4 Cool
But I find your question unclear since you write "Ignoring the nature of the output". And you explicitly create factors in to data.frame
, so I'm unsure exactly what you expected. Remember that factor
s in R are integer vectors with labels. That is what you are seeing in your print.
Edit:
test1 <- lapply(dummy, "[[", 1)
as.data.frame(do.call(cbind, test1))
# A B
#1 Boy Boy
#2 He Not
#3 Is So
#4 Cool Cool
Edit2 From discussion in the comments, does any of these work?
test1 <- lapply(dummy, unlist)
as.data.frame(do.call(cbind, test1))
# Same output as above
Alternatively:
data.frame(unlist(test1, recursive = FALSE))
# Same output as above
Upvotes: 2