dplyr:summary_at 中的自定义函数 [英] dplyr: custom function in summarize_at

查看:33
本文介绍了dplyr:summary_at 中的自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to use my own function smd in summarize_at, without success. If I try to do:

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)) 也行不通!

Doesn't work!! Try to make funs(smd)and funs(sd/sqrt(n()-1)) and dosen't work too!

请问,有什么想法吗?

推荐答案

第一个变化是将 na.rm= 传递给 sd(.),所以>

First change is to pass na.rm= on to sd(.), so

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

As @astrofunkswag suggested, though, you need to consider if NA values should decrease your length. For that, we need to replace length(x) with 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

这篇关于dplyr:summary_at 中的自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆