Reputation: 11
I know the standard aggregate function, example code
aggregate(hp~cyl/vs, data=mtcars, FUN="sum", na.rm=TRUE)
that returns:
cyl vs hp
1 4 0 91
2 6 0 395
3 8 0 2929
4 4 1 818
5 6 1 461
However i would like to put the "vs" in the columns, like this:
vs 0 1
cyl hp hp
1 4 91 818
2 6 395 461
3 8 2929
How can this be done in R?
Upvotes: 1
Views: 94
Reputation: 9123
You can use xtabs()
directly on the mtcars
data, without using aggregate()
as an intermediate step:
xtabs(hp ~ cyl + vs, data = mtcars)
Upvotes: 1
Reputation: 512
Here is a data.table
answer:
mt = as.data.table(mtcars)
dcast.data.table(mt, cyl ~ vs, value.var="hp", fun.agg = sum)
# cyl 0 1
# 1: 4 91 818
# 2: 6 395 461
# 3: 8 2929 0
Upvotes: 1
Reputation: 887223
Try xtabs
xtabs(hp~cyl+vs, res)
# vs
#cyl 0 1
# 4 91 818
# 6 395 461
# 8 2929 0
res <- aggregate(hp~cyl/vs, data=mtcars, FUN=sum, na.rm=TRUE)
Upvotes: 1