[R] function "Stack"

David Winsemius dwinsemius at comcast.net
Tue Mar 25 02:46:08 CET 2014


On Mar 24, 2014, at 9:02 AM, Tham Tran wrote:

> 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 did not create your stack function which would have masked the base function. You would probably not want to do that. Better to name it `mystack` or somesuch. Yours looks very similar to the code of the utils::stack.

getAnywhere(stack.data.frame)

function (x, select, ...) 
{
    if (!missing(select)) {
        nl <- as.list(1L:ncol(x))
        names(nl) <- names(x)
        vars <- eval(substitute(select), nl, parent.frame())
        x <- x[, vars, drop = FALSE]
    }
    keep <- unlist(lapply(x, is.vector))
    if (!sum(keep)) 
        stop("no vector columns were selected")
    if (!all(keep)) 
        warning("non-vector columns will be ignored")
    x <- x[, keep, drop = FALSE]
    data.frame(values = unlist(unname(x)), ind = factor(rep.int(names(x), 
        lapply(x, length))), stringsAsFactors = FALSE)
}


> stack(df)  # the utils::stack.data.frame
  values ind
1      3   a
2      5   a
3      2   b
4      8   b
5      9 a.1
6      1 a.1
7      6 b.1
8      4 b.1

It would be pretty easy to reassign the items with dots in the ind factor and 

rbind(stack(df[1:2]), stack(df[3:4]) )
#---------
  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

-- 
David.

> 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.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA




More information about the R-help mailing list