Question

I would like to aggregate a data.frame over 3 categories, with one of them varying. Unfortunately this one varying category contains NAs (actually it's the reason why it needs to vary). Thus I created a list of data.frames. Every data.frame within this list contains only complete cases with respect to three variables (with only one of them changing).

Let's reproduce this:

library(plyr)

mydata <- warpbreaks
names(mydata) <- c("someValue","group","size")
mydata$category <- c(1,2,3)
mydata$categoryA <- c("A","A","X","X","Z","Z")
# add some NA
mydata$category[c(8,10,19)] <- NA
mydata$categoryA[c(14,1,20)] <- NA 

# create a list of dfs that contains TRUE FALSE
noNAList <- function(vec){
res <- !is.na(vec)
return(res)
}

testTF <- lapply(mydata[,c("category","categoryA")],noNAList)

# create a list of data.frames
selectDF <- function(TFvec){
res <- mydata[TFvec,]
return(res)
}

# check x and see that it may contain NAs as long
# as it's not in one of the 3 categories I want to aggregate over    
x <-lapply(testTF,selectDF)

## let's ddply get to work
doddply <- function(df){
ddply(df,.(group,size),summarize,sumTest = sum(someValue))
}

y <- lapply(x, doddply);y

y comes very close to what I want to get

$category
group size sumTest
1     A    L     375
2     A    M     198
3     A    H     185
4     B    L     254
5     B    M     259
6     B    H     169

$categoryA
group size sumTest
1     A    L     375
2     A    M     204
3     A    H     200
4     B    L     254
5     B    M     259
6     B    H     169

But I need to implement aggregation over a third varying variable, which is in this case category and categoryA. Just like:

group size category sumTest sumTestTotal      
1      A    H        1      46          221 
2      A    H        2      46          221 
3      A    H        3      93          221 

and so forth. How can I add names(x) to lapply, or do I need a loop or environment here?

EDIT: Note that I want EITHER category OR categoryA added to the mix. In reality I have about 15 mutually exclusive categorical vars.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top