gpt4 book ai didi

r - FUN(X[[i]],...) 中的错误 : only defined on a data frame with all numeric variables

转载 作者:行者123 更新时间:2023-12-02 20:19:15 24 4
gpt4 key购买 nike

我不断收到提到的错误,我唯一想做的就是运行一个简单的 sum() 函数。这里的数据来自基础数据集包,您可以在第一行代码 data(UCBAdmissions) 中将其加载到 R session 中。

data(UCBAdmissions)
data <- data.frame(UCBAdmissions)

data %>%
filter(Gender == "Female") %>%
summarise(
sum(Freq)
)

通过这样做,代码可以工作,但我不明白为什么没有 summarise() 函数就不起作用

我唯一想知道的是数据中女性的数量。如果你们能想到更好的解决方案请告诉我

最佳答案

这里有五个解决方案,其中 4 个仅基于 R,还有一个 dplyr 解决方案。

library(dplyr)


with(data, sum(Freq[Gender == "Female"]))
#[1] 2662

sum(data[data$Gender == "Female", "Freq"])
#[1] 2662

with(data, tapply(Freq, Gender, sum))
# Male Female
# 2162 2662


aggregate(Freq ~ Gender, data, sum)
# Gender Freq
#1 Male 2162
#2 Female 2662

data %>% group_by(Gender) %>% summarise(Total = sum(Freq))
## A tibble: 2 x 2
# Gender Total
# <fct> <int>
#1 Male 2162
#2 Female 2662

现在对 5 种方法进行基准测试。

library(ggplot2)
library(microbenchmark)

mb <- microbenchmark(
sum1 = with(data, sum(Freq[Gender == "Female"])),
sum2 = sum(data[data$Gender == "Female", "Freq"]),
tapply = with(data, tapply(Freq, Gender, sum)),
agg = aggregate(Freq ~ Gender, data, sum),
dplyr = data %>% group_by(Gender) %>% summarise(Total = sum(Freq))
)

mb
#Unit: microseconds
# expr min lq mean median uq max neval
# sum1 58.946 72.9495 92.31978 86.7075 102.7015 317.988 100
# sum2 139.752 171.6000 197.02931 187.4195 213.3305 323.226 100
# tapply 178.584 208.8955 237.48214 237.8795 259.6350 366.596 100
# agg 2824.940 2959.0000 3194.69868 3070.5720 3343.5465 5156.801 100
# dplyr 3239.238 3361.0070 4377.61585 3506.0325 3753.1655 82005.883 100

基础 R 解决方案显然更快。

microbenchmark 图表需要 ggplot2

autoplot(mb)

enter image description here

关于r - FUN(X[[i]],...) 中的错误 : only defined on a data frame with all numeric variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51810783/

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