[R] How to reshape this data frame from long to wide ?

Berwin A Turlach berwin at maths.uwa.edu.au
Sun Feb 22 05:54:05 CET 2009


G'day Darren,

On Sun, 22 Feb 2009 11:23:27 +0800
Daren Tan <darentan76 at gmail.com> wrote:

> I tried cast and melt in reshape package, but still can't convert
> this data frame m
> 
> m
>      [,1] [,2]
> [1,] "A"  "1"
> [2,] "A"  "2"
> [3,] "B"  "3"

from the output, this does not look like a data frame to me but like a
matrix.

> to this form.
> 
> m1
>      [,1] [,2]
> [1,] "A"  "B"
> [2,] "1"  "3"
> [3,] "2"  NA

I don't think that this result can be achieved.  "A" and "B" would
become the column names in the newly created data frame but not be
entries in the data frame themselves.

I presume you are looking for something like:

R> m <- data.frame(var=c("A", "A", "B"), value=c("1", "2", "3"))
R> m
  var value
1   A     1
2   A     2
3   B     3
R> m$id <- c(1,2,1)
R> m
  var value id
1   A     1  1
2   A     2  2
3   B     3  1
R> library(reshape)
R> ( res <- cast(m, id~...) )
  id A    B
1  1 1    3
2  2 2 <NA>
R> res[,  !(names(res) %in% "id")]
  A    B
1 1    3
2 2 <NA>

HTH.

Cheers,

	Berwin

=========================== Full address =============================
Berwin A Turlach                            Tel.: +65 6516 4416 (secr)
Dept of Statistics and Applied Probability        +65 6516 6650 (self)
Faculty of Science                          FAX : +65 6872 3919       
National University of Singapore     
6 Science Drive 2, Blk S16, Level 7          e-mail: statba at nus.edu.sg
Singapore 117546                    http://www.stat.nus.edu.sg/~statba




More information about the R-help mailing list