screechOwl
screechOwl

Reputation: 28159

R: aggregate based on factor or numeric

I'm trying to aggregate some data that is both numeric and factor variables. If the variable is numeric I'd like the mean. If it's a factor I'd like the most frequently occurring value. I've written the following function but am not getting the output I'd like:

meanOrMostFreq <- function(x){
    if(class(x) == 'factor'){
    tbl <- as.data.frame(table(x))
    tbl$Var1 <- as.character(tbl$Var1)
    return(tbl[tbl$Freq == max(tbl$Freq),'Var1'][1])
    }
    if(class(x) == 'numeric'){
    meanX <- mean(x, na.rm = TRUE)
    return(meanX)
    }
}

Here's how I'm using it:

df1 <- iris[1:148,]
df1$letter1 <- as.factor(rep(letters[1:4], 37))

momf <- aggregate(.~ Species, df1, FUN = function(x) meanOrMostFreq(x))

And the results:

> momf
     Species Sepal.Length Sepal.Width Petal.Length Petal.Width letter1
1     setosa     5.006000    3.428000     1.462000       0.246    2.46
2 versicolor     5.936000    2.770000     4.260000       1.326    2.54
3  virginica     6.610417    2.964583     5.564583       2.025    2.50

I'm hoping to get an actual letter in the last column instead of a number. Any suggestions on what I'm doing wrong?

Upvotes: 3

Views: 1532

Answers (3)

Athos
Athos

Reputation: 660

A alternative using plyr package:

ddply(df1, .(Species), function(df) {
    sapply(df, meanOrMostFreq)
})

[]'s

Upvotes: 1

Neal Fultz
Neal Fultz

Reputation: 9687

Going through the formula interface to aggregate apparently loses the metadata that its' a factor; this worked for me:

> meanOrMostFreq
function(x){
    if(class(x) == 'factor'){
    return(  names(which.max(table(x))) )
    }
    if(class(x) == 'numeric'){
    meanX <- mean(x, na.rm = TRUE)
    return(meanX)
    }
}
> aggregate(df1[-5], df1[5], meanOrMostFreq)
     Species Sepal.Length Sepal.Width Petal.Length Petal.Width letter1
1     setosa     5.006000    3.428000     1.462000       0.246       a
2 versicolor     5.936000    2.770000     4.260000       1.326       c
3  virginica     6.610417    2.964583     5.564583       2.025       a

Since there is different behavior for aggregate.formula and aggregate.data.frame this feels like a bug to me.

Upvotes: 1

akrun
akrun

Reputation: 887138

Here's a way using data.table

library(data.table)
setDT(df1)[ ,lapply(.SD, function(x) if(is.numeric(x)) mean(x, na.rm=TRUE) else
          names(which.max(table(x)))) , by=Species]

#         Species Sepal.Length Sepal.Width Petal.Length Petal.Width letter1
#1:     setosa     5.006000    3.428000     1.462000       0.246       a
#2: versicolor     5.936000    2.770000     4.260000       1.326       c
#3:  virginica     6.610417    2.964583     5.564583       2.025       a

Upvotes: 5

Related Questions