[R] function "Stack"
Noah Marconi
noah.marconi at noah-marconi.com
Mon Mar 24 21:37:24 CET 2014
The reshape2 package may be what you're looking for:
http://cran.r-project.org/web/packages/reshape2/index.html
install.packages("reshape2")
reshape2::melt(df)
On 2014-03-24 12:02, 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 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.
More information about the R-help
mailing list