[R] function "Stack"

Tham Tran hanhtham.tran at yahoo.com.vn
Mon Mar 24 17:02:29 CET 2014


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




--
View this message in context: http://r.789695.n4.nabble.com/function-Stack-tp4687449.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list