【问题标题】:Passing in multiple arguements to apply/sapply sytnax [closed]将多个参数传递给应用/应用语法 [关闭]
【发布时间】:2016-07-25 20:10:24
【问题描述】:

这里是新手 - 无法弄清楚一些基本语法,并且考虑到 google isnt help....这些词的共同性......

mtcars$testcol = 'testing'
imgood = sapply(mtcars, IQR, na.rm=T) #works ok... helpme =
sapply(mtcars, quantile c(.3,.9, .95, na.rm=TRUE)  #don't know how to

那我想做的只是

mtcars$mynewcolumn = imgood....etc

使用 sapply/apply 传入参数...

我也一直在使用 dplyr:: 查看 summarise_each、summarise_all 有没有办法在这里工作?

【问题讨论】:

  • sapply(mtcars, function(x) { quantile(x,c(.3,.9, .95, na.rm=TRUE)) }) 怎么样?
  • 这是一个错字。你漏了一个逗号sapply(mtcars, quantile, c(.3,.9, .95, na.rm=TRUE))
  • 这有效,直到我像上面那样添加一个非数字列。我尝试了类似 ----sapply(mtcars, function(x) {ifelse(is.numeric(x), quantile(x,c(.3,.9, na.rm=TRUE)),'xxx') }) ---- 但是我没有得到多重值的输出
  • 然后只在数字列上运行它;无论如何,为非数字列计算 IQR 是没有意义的。还是我们错过了什么?向我们展示您的开始和想要结束的内容可能会有所帮助,然后再告诉我们您的尝试。
  • @Aaron 是对的。获取字符向量的百分位数是没有意义的。因此,函数的名称 quantile.

标签: r apply sapply


【解决方案1】:

很遗憾,quantile 并非旨在返回 NA 向量或单个 NA。为了实现这一点,您可以编写一个封闭函数,按照您希望的方式运行:

my_quantile <- function(x, ...) if ( is.numeric(x) ) {quantile(x,...)} else {
                                                 z <- list(...)[[1]]; rep(NA,length(z))}

> sapply(mtcars, my_quantile, c(.3,.9, .95), na.rm=TRUE)
      mpg cyl   disp     hp   drat      wt    qsec vs am gear carb testcol
30% 15.98   4 142.06 106.20 3.1500 2.77300 17.0200  0  0    3  2.0      NA
90% 30.09   8 396.00 243.50 4.2090 4.04750 19.9900  1  1    5  4.0      NA
95% 31.30   8 449.00 253.55 4.3145 5.29275 20.1045  1  1    5  4.9      NA

这可能不是您要编写的第一个函数,因为它需要提取传递给 quantile 的第二个参数以重复 NA 的次数以匹配其他分位数,这反过来又允许 sapply 重新运行矩阵而不是列表.它也会有点脆弱,因为你没有命名你的论点。如果 probs 已被命名,那么它可能不是第一个,因此最好检查 match.args 是否可以找到 probs 参数,然后,如果失败,则使用第一个参数...-argument-list。

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 2016-01-17
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    相关资源
    最近更新 更多