开发者

How to transform a data frame into a matrix with group values in rows and columns?

开发者 https://www.devze.com 2023-04-01 07:10 出处:网络
I ran a piece of code like this x = data.frame(numerator = 1:3, value = letters[1:3],value1=letters[4:6])

I ran a piece of code like this

x = data.frame(numerator = 1:3, value = letters[1:3],value1=letters[4:6])
xa = aggregate(list(x$numerator),by=list(x$value,x$value1),FUN=sum)

But the result xa is formatted like this

 Group.1 Group.2开发者_如何学JAVA X1.3
1       a       d    1
2       b       e    2
3       c       f    3

I would like my results to be organised in a matrix format such that the rows are represented by the Group.1 values and the columns are represented by the Group.2 values, like the following:

    d e f
a   1 NULL NULL
b   NULL 2 NULL
c   NULL NULL 3

How do I do that?


You can use daply from plyr package.

xa = daply(.data=x,
           .variables=c("value","value1"),
           .fun=function(x) sum(x$numerator))


We can use a BASE R function:

  tapply(x$numerator,x[,2:3],I)
        value1
value  d  e  f
    a  1 NA NA
    b NA  2 NA
    c NA NA  3


Another option is using xtabs from the stats-package:

x = data.frame(numerator = 1:3, value = letters[1:3],value1=letters[4:6])

Then you use the aggregate function like you did:

xa = aggregate(list(x$numerator),by=list(x$value,x$value1),FUN=sum)

And the conversion to a nice matrix is done via

xb<-xtabs(X1.3~Group.1+Group.2,xa)


    Group.2
Group.1 d e f
      a 1 0 0
      b 0 2 0
      c 0 0 3

Note that unlike in the solutions above NULL or NA values are here shown as 0.

0

精彩评论

暂无评论...
验证码 换一张
取 消