【问题标题】:dplyr: custom function in summarize_atdplyr:summary_at 中的自定义函数
【发布时间】:2020-10-08 21:30:03
【问题描述】:

我想在summarize_at 中使用我自己的函数smd,但没有成功。如果我尝试这样做:

library(dplyr)

# My function
smd<-function(x,...)
  {sd(x)/sqrt(length(x)-1)}

starwars %>%
  summarise_at(c("height", "mass"), smd, na.rm = TRUE)

Erro: C stack usage  15924224 is too close to the limit

没有用!!尝试使funs(smd)funs(sd/sqrt(n()-1)) 也不起作用!

请问有什么想法吗?

【问题讨论】:

  • 您的代码在我的机器上运行良好,只是它只返回 NAs
  • 您可以将... 包含在sd 函数中,这将修复错误,但这也会改变长度,因此您需要考虑这一点

标签: r dplyr tidyverse


【解决方案1】:

第一个更改是将na.rm= 传递给sd(.),所以

smd <- function(x, ...) sd(x, ...)/sqrt(length(x)-1)
starwars %>%
  summarise_at(c("height", "mass"), smd, na.rm=TRUE)
# # A tibble: 1 x 2
#   height  mass
#    <dbl> <dbl>
# 1   3.75  18.3

不过,正如@astrofunkswag 所建议的,您需要考虑NA 值是否应该减少您的长度。为此,我们需要将length(x) 替换为sum(!is.na(x))

smd <- function(x, ...) sd(x, ...)/sqrt(sum(!is.na(x))-1)
starwars %>%
  summarise_at(c("height", "mass"), smd, na.rm=TRUE)
# # A tibble: 1 x 2
#   height  mass
#    <dbl> <dbl>
# 1   3.89  22.3

【讨论】:

  • 如果我在starwars%&gt;% group_by(gender) %&gt;% summarise_at(c("height", "mass"), smd, na.rm=TRUE) 中使用group_by 不起作用,为什么@r2evans 不起作用?错误:summarise() 输入 height 有问题。 x 未使用的参数 (na.rm = TRUE) i 输入 height(function (x, ...) ...。 i 错误发生在第 1 组:性别 = “女性”。运行 rlang::last_error() 以查看错误发生的位置。
【解决方案2】:

我们也可以通过summarise/across 做到这一点

smd <- function(x, ...) sd(x, ...)/sqrt(sum(complete.cases(x))-1)
starwars %>%
     summarise(across(c(height, mass), smd, na.rm = TRUE))

-输出

# A tibble: 1 x 2
#  height  mass
#   <dbl> <dbl>
#1   3.89  22.3


  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多