Convert list returned by sapply() to a data.frame

9.4k views Asked by At

I have a list returned by sapply()

$my.list <- sapply()  
$my.list  
"var1" "var2" "var3"  
 1.1    2.5    3.2

The ideal result is to transform my.list into a data frame df:

$df  
"var1"  1.1  
"var2"  2.5  
"var3"  3.2

I have tried to 'subset' each row of my.list as follows:

$p1 <- names(my.list)  
$p1  
   "var1" "var2" "var3"  
$p2 <- as.vector(my.list)
$p2 
   1.1 2.5 3.2

But then I had no further luck cbind/rbind-ing these row vectors into a data frame. Any thoughts/suggestions? Thanks.

4

There are 4 answers

0
Prradep On BEST ANSWER

I am not sure whether this is what you require.

my.list <- as.data.frame(sapply(trees,mean))
my.list <- cbind(my.list,rownames(my.list))
rownames(my.list) <- NULL

I'm sure there might be some other smart ways to do it !

1
remi On

Binding p1 and p2 into df is similar to question #12787551

Here is the solution: To remove the levels in p1 (factor)

$p1 <- as.numeric(names(my.list))

Then to construct df

$df <- cbind(data.frame(p1),p2)

The ideal result will then return:

$dim(df)
3 2
$df$p1
var1 var2 var3
1
BrodieG On

If I understand your question correctly, you can use stack. Here I make up a named "list" (really a vector) as you might get from sapply. Note this works even if your data is actually a list.

> my.list <- setNames(1:3, letters[1:3])
> my.list
a b c 
1 2 3
> stack(my.list)
  values ind
1      1   a
2      2   b
3      3   c
2
DeanAttali On

Not 100% this is what you want, is this what you mean?

my.list <- sapply(letters[1:3], toupper)
data.frame(t(my.list))

(Next time please provide us with your input to make it easier to answer)