这里的新闻 - 无法弄清楚一些基本的语法,并给出了谷歌没有帮助的常识......
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 ...传递参数
此外,我一直在查看summarise_each,summarise_all和dplyr :: 有没有办法在这里工作?
答案 0 :(得分: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
它可能不是你要编写的第一个函数,因为它需要提取传递给分位数的第二个参数来重复NA的次数以匹配其他分位数,这反过来允许sapply
重新启动矩阵而不是一个列表。它也会有点脆弱,因为你没有命名你的论点。如果probs
已被命名,那么它可能不是第一个,所以最好检查match.args
是否可以找到probs
参数,然后,如果失败,使用...
- 参数列表中的第一个参数。