2014-10-06 35 views
3

我想聚合一些既是數字又是因子變量的數據。如果變量是數字,我想要的意思。如果這是一個因素,我希望獲得最頻繁的價值。我已經寫了下面的功能,但我沒有得到輸出,我想:R:基於因子或數字的聚合

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) 
    } 
} 

這裏是我如何使用它:

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

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

而且結果:

> 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 

我希望在最後一列而不是數字中得到一個實際的字母。任何建議我做錯了什麼?

+0

很肯定'aggregate'不會與非NUMERICS玩。您可能只需要一個不同的工具。 – joran 2014-10-06 16:18:50

+0

你可以通過'data.table'輕鬆實現你想要的。無論如何,在你的'ôMoreOrMostFreq'有一些錯誤。首先,它應該是'as.data.frame(table(x))'。那麼結果列將被命名爲'x'而不是'Var'。您在'聚合「調用中看不到這些錯誤,因爲它強制轉換爲數字。只要嘗試'meanOrMostFreq(df1 $ letters)'。 – nicola 2014-10-06 16:35:32

+0

@nicola:你在表格(x)和var與Var1上是正確的。我做了更改,但仍然遇到同樣的錯誤。 – screechOwl 2014-10-06 16:44:06

回答

5

下面是使用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 
1

通過式接口aggregate去明顯失去其一個因子中的元數據的方式;這個工作對我來說:

> 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 

既然有不同的行爲aggregate.formulaaggregate.data.frame這種感覺就像我的錯誤。

1

使用plyr包一個選擇:

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

的[]