Given a data.frame like this
> x <- data.frame(A=c('a','a','b','b'), B=c(1,2,3,4))
> x
A B
1 a 1
2 a 2
3 b 3
4 b 4
I'd like to transform it into
a b
1 1 3
2 2 4
It should be a simple operation, but I can't figure out how to do it.
The closest I've got to is cast(x, . ~ A)
which at least doesn't
fail with "undefined columns selected" but it's still not what I want.
Any help appreciated.
I have also been struggling to understand cast
recently. Your desired output shows the values 1
and 3
on the same line. But your input doesn't provide that information. Adding an id
column solves the issue.
library(reshape2)
x <- data.frame(id=c(1, 2, 1, 2), A=c('a', 'a', 'b', 'b'), B=c(1, 2, 3, 4))
dcast(x, id ~ A, value.var="B")
# id a b
# 1 1 1 3
# 2 2 2 4
Like this:
data.frame( tapply(x$B, x$A, list))
Result:
a b
1 1 3
2 2 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With