1

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.

remi
  • 781
  • 2
  • 13
  • 22

4 Answers4

2

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 !

Prradep
  • 5,506
  • 5
  • 43
  • 84
1

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
BrodieG
  • 51,669
  • 9
  • 93
  • 146
  • stack() looks useful except that it keeps "levels" of element "ind" of my.list as returned by sapply(). Let's say: ps <- stack(my.list). ps$values is good. But ps$ind returns levels in addition to values. This will cause problems in processing ps further. – remi Jun 10 '15 at 01:01
1

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)

DeanAttali
  • 25,268
  • 10
  • 92
  • 118
  • If df <- data.frame(t(my.list)) then dim(df) return: 1 3 -- 3 observations of 1 variable. This is not the desired outcome. The ideal outcome in my example is to have dim(df) return: 3 2 -- 3 observations of 2 variables. Shall edit the question? – remi Jun 10 '15 at 01:07
  • It's actually one observation of 3 variables. Based on your input, that seemed to make sense - you had "var1" "var2" and "var3" , one value for each. I'm not sure what you want the output to look like... please be more clear. – DeanAttali Jun 10 '15 at 03:59
0

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
remi
  • 781
  • 2
  • 13
  • 22
  • to question: 12787551 http://stackoverflow.com/questions/12787551/creating-a-data-frame-from-two-vectors-using-cbind – remi Jun 10 '15 at 01:49