An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20090222/3ab72552/attachment-0001.pl>
How to reshape this data frame from long to wide ?
3 messages · Daren Tan, Berwin A Turlach, Gabor Grothendieck
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
Not completely clear what you want (it does not appear to be a conventional reshape) but try this:
m <- matrix(c("A", "A", "B", "1", "2", "3"), 3, 2)
structure(do.call(cbind, lapply(tapply(m[,2], m[,1], c), ts)), tsp = NULL, class = NULL)
A B [1,] "1" "3" [2,] "2" NA
On Sat, Feb 21, 2009 at 10:23 PM, 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"
to this form.
m1
[,1] [,2]
[1,] "A" "B"
[2,] "1" "3"
[3,] "2" NA
Please help.
[[alternative HTML version deleted]]
______________________________________________ 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.