Reputation: 1617
I am trying to sum TRUE values for two variables using a third columns but I am getting an error. Here is a code sample:
framea<-data.frame(v1=c(TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, NA, TRUE, TRUE, TRUE, FALSE),
v2=c(FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, NA, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE),
v3=c("Blue", "Red","Blue", "Red","Blue", "Red","Blue", "Red","Blue", "Red","Blue", "Red","Blue"),
v4=c(1:4, 1:4, 1:5))
framea
attach(framea)
aggdata<-aggregate(formula=cbind(v1, v2)~v4, data=framea, by=list(v3), FUN=sum, na.rm = TRUE, na.action = NULL)
detach(framea)
aggdata
After the aggregate() step I get the following error:
Error in FUN(X[[i]], ...) : invalid 'type' (list) of argument
I ideally want something like the following output for aggdata:
v1 v2
1 Blue 1 0
2 Blue 1 1
3 Blue 0 2
4 Blue 0 0
1 Red 2 2
2 Red 1 1
3 Red 1 1
How can I accomplish this?
Upvotes: 1
Views: 9390
Reputation: 1617
I figured it out thanks to the post from akrun above. I shouldn't have been using the formula= capability. Here is the answer:
framea<-data.frame(v1=c(TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, NA, TRUE, TRUE, TRUE, FALSE),
v2=c(FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, NA, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE))
v3<-c("Blue", "Red","Blue", "Red","Blue", "Red","Blue", "Red","Blue", "Red","Blue", "Red","Blue")
v4<-c(1:3, 1:3, 1:3, 1:4)
framea
attach(framea)
aggdata<-aggregate(x=framea, by=list(v3, v4),FUN=sum, na.rm = TRUE, na.action = NULL)
detach(framea)
aggdata
(Let me know if I should delete this instead. Thanks.)
Upvotes: 2