how to transform data frame in r

88 views Asked by At

I have a data frame

newDF<-data.frame(type=c(rep("A",4),
                  rep("B",2),rep("C",3),
                  rep("D",4),rep("E",4)), 
                  cluster=sample(1:4,17,replace=T), 
                  count=sample(1:20, 17, rep=T), 
                  sum=sample(30:1000,17,rep=T))

And I need to get 2 new data frames, which would have "cluster" as columns, type as rows and count as fill.(second table will be the same, but fill=sum, not count). There must be some NA's in these 2 tables, because newDF has 17 rows, but two new data frames must be 5x5

How can I create these 2 5x5 data frames?

2

There are 2 answers

3
Slavka On

I'm sorry, I have already found answer

spread(newDF[,-3],key=cluster, value=sum)
0
Froom2 On

Try this:

library(reshape2)
countoutput <- dcast(newDF,type~cluster,value.var = "count",fun.aggregate = sum)
sumoutput <- dcast(newDF,type~cluster,value.var = "sum",fun.aggregate = sum)

It fills missing values with 0, but you could specify a different number (e.g. -1) by adding the argument fill = -1 to help highlight which are missing values... I can't seem to get it to put NA instead of 0, but I haven't tried for very long.