I want to convert a list to a data frame, with the following code:
ls<-list(a=c(1:4),b=c(3:6))
do.call("rbind",ls)
The result obtained by adding do.call is as shown below. It returns a data.frame
object as desired.
do.call("rbind",ls)
[,1] [,2] [,3] [,4]
a 1 2 3 4
b 3 4 5 6
However if I directly use rbind
, it returns a list.
Why does rbind
behave differently in these two situations?
my.df<-rbind(ls)
str(ls)
my.df
a b
ls Integer,4 Integer,4
str(ls)
List of 2
$ a: int [1:4] 1 2 3 4
$ b: int [1:4] 3 4 5 6
do.call("rbind", ls)
returns a matrix, not a data frame. Same withrbind(ls)
. – Aporiado.call
extracts the elements out of the list- that's the difference. As if you would dorbind(ls[[1]], ls[[2]])
– Choughrbind(ls)
is still a list. Actually what I want is to convert a list to a matrix – Multiplicationrbind(ls)
is a matrix. It contains list elements. Seeclass(rbind(ls))
– Aporia> str(ls)
, it says it is a list. Though both do.call("rbind", ls) and rbind(ls) return a matrix, the outcome of them are different – Multiplication?do.call
– Donndonna