[R] function "Stack"

arun smartpink111 at yahoo.com
Mon Mar 24 17:45:20 CET 2014


Hi,
You may try:
library(reshape2)
res <- setNames(melt(as.matrix(df))[,c(3,2)],c("values","ind"))
 res2 <- stack(df, check.names = FALSE) 
 identical(res,res2)
#[1] TRUE
A.K.


Dears R Users, 

I have another question on function "stack". 

Given a data frame like: 
df=data.frame(a=c(3,5),b=c(2,8),a=c(9,1),b=c(6,4),check.names=F) 
   a b a b 
   3 2 9 6 
   5 8 1 4 
  
I would like to form a new data frame like: 
    values ind 
1      3   a 
2      5   a 
3      2   b 
4      8   b 
5      9   a 
6      1   a 
7      6   b 
8      4   b 

I arrived with the script: 
    stack = function (x, ...) 
{ 
    x = as.list(x) 
    keep = unlist(lapply(x, is.vector)) 
    if (!sum(keep)) 
        stop("at least one vector element is required") 
    if (!all(keep)) 
        warning("non-vector elements will be ignored") 
    x = x[keep] 
    data.frame(values = unlist(unname(x)), ind = factor(rep.int(names(x), 
        lapply(x, length))), stringsAsFactors = FALSE, ...) 
} 
     stack(df, check.names = FALSE) 

Do you have any other simple manner to that? 

Thanks in advance for your helps! 

Tham




More information about the R-help mailing list