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

标签 r

我不断收到提到的错误,我唯一想做的就是运行一个简单的 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/

相关文章:

r - 在 Rmarkdown 的 YAML header 中设置数字的标题字体大小

r - 在 mutate() 中使用 Weighted.mean() 创建行加权平均值

r - 使用 while 循环而不打印所有迭代

r - 在 R 中使用 mutate 重命名列中的项目

r - R 中带有 mutate 和 case_when 的用户定义函数

r - 算术运算符是否比算术函数更可取?

r - 将 apply 的输出合并到 R 中的数组中

r - 将 WinBUGS 模型转换为 JAGS(使用 R)

r - append 到具有动态名称的列表

在 R 中读取具有重复行名称的 csv 文件