Reputation: 581
I have dataset that looks like this but much larger:
data <- data.frame(cbind(c(1,1,1,1,1,1,2,2,2),
c(1,1,1,2,2,2,1,1,1),
c(1,2,2,2,3,3,1,2,1)))
data$X3<-factor(data$X3)
levels(data$X3)<-c("House","Barn","Pigsty")
I want to have a dataset with counts of "House," "Barn," and "Pigsty" by X1
and X2
. Imagine that X and Y are coordinates and that I want to count how many of each type of building I have at each coordinate.
I am doing:
agdata <- aggregate(data[,"X3"],by=list(data[,"X1"],data[,"X2"]),FUN=table)
If I ask to print agdata
by using head(agdata)
, it shows me the two coordinates and the three count variables for each level of X3
:
> head(agdata)
Group.1 Group.2 x.House x.Barn x.Pigsty
1 1 1 1 2 0
2 2 1 2 1 0
3 1 2 0 1 2
However, if I use View(agdata) I only see three variables Group.1
,Group2
,and x
.
How can I get aggregate
to give me a dataset in the format that I see when I use head(agdata)
?
Upvotes: 0
Views: 137
Reputation: 2498
You could get it using dcast from reshape2 package:
library(reshape2)
dcast(data, X1+X2 ~ X3)
Upvotes: 1