gpt4 book ai didi

R:基于因子或数字的聚合

转载 作者:行者123 更新时间:2023-12-01 09:56:18 25 4
gpt4 key购买 nike

我正在尝试聚合一些既是数字变量又是因子变量的数据。如果变量是数字,我想要平均值。如果这是一个因素,我想要最常出现的值。我编写了以下函数,但没有得到我想要的输出:

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

我希望在最后一列中得到一个实际的字母而不是数字。对我做错了什么有什么建议吗?

最佳答案

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

关于R:基于因子或数字的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26220179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com