I sent that last email too quickly, the duplicate column names cause a problem when melting. Transposing the data frame first gets around it:

reshape2::melt(t(df))[c('Var1', 'value')]

  Var1 value
1    a     3
2    b     2
3    a     9
4    b     6
5    a     5
6    b     8
7    a     1
8    b     4

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@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.

______________________________________________
R-help@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.

Reply via email to