Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cast() to transform a data.frame

Tags:

dataframe

r

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.

like image 209
Ernest A Avatar asked Feb 21 '23 18:02

Ernest A


2 Answers

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 image 102
bdemarest Avatar answered Feb 23 '23 16:02

bdemarest


Like this:

data.frame( tapply(x$B, x$A, list))

Result:

  a b
1 1 3
2 2 4
like image 21
IRTFM Avatar answered Feb 23 '23 16:02

IRTFM