r - 有 pmin 和 pmax 分别取 na.rm,为什么没有 psum?

标签 r

似乎 R 可能缺少一个明显的简单函数:psum .它是否以不同的名称存在,还是在某个包中?

x = c(1,3,NA,5)
y = c(2,NA,4,1)

min(x,y,na.rm=TRUE)    # ok
[1] 1
max(x,y,na.rm=TRUE)    # ok
[1] 5
sum(x,y,na.rm=TRUE)    # ok
[1] 16

pmin(x,y,na.rm=TRUE)   # ok
[1] 1 3 4 1
pmax(x,y,na.rm=TRUE)   # ok
[1] 2 3 4 5
psum(x,y,na.rm=TRUE)
[1] 3 3 4 6                             # expected result
Error: could not find function "psum"   # actual result

我意识到 +已经喜欢 psum ,但是 NA 呢? ?
x+y                      
[1]  3 NA NA  6        # can't supply `na.rm=TRUE` to `+`

有没有案例添加psum ?或者我错过了什么。

这个问题是这个问题的后续:
Using := in data.table to sum the values of two columns in R, ignoring NAs

最佳答案

继@JoshUlrich 对上一个问题的评论之后,

psum <- function(...,na.rm=FALSE) { 
    rowSums(do.call(cbind,list(...)),na.rm=na.rm) } 

编辑 :来自斯文·海恩斯坦:
psum2 <- function(...,na.rm=FALSE) { 
    dat <- do.call(cbind,list(...))
    res <- rowSums(dat, na.rm=na.rm) 
    idx_na <- !rowSums(!is.na(dat))
    res[idx_na] <- NA
    res 
}

x = c(1,3,NA,5,NA)
y = c(2,NA,4,1,NA)
z = c(1,2,3,4,NA)

psum(x,y,na.rm=TRUE)
## [1] 3 3 4 6 0
psum2(x,y,na.rm=TRUE)
## [1] 3 3 4 6 NA

n = 1e7
x = sample(c(1:10,NA),n,replace=TRUE)
y = sample(c(1:10,NA),n,replace=TRUE)
z = sample(c(1:10,NA),n,replace=TRUE)

library(rbenchmark)
benchmark(psum(x,y,z,na.rm=TRUE),
          psum2(x,y,z,na.rm=TRUE),
          pmin(x,y,z,na.rm=TRUE), 
          pmax(x,y,z,na.rm=TRUE), replications=20)

##                          test replications elapsed relative 
## 4  pmax(x, y, z, na.rm = TRUE)           20  26.114    1.019 
## 3  pmin(x, y, z, na.rm = TRUE)           20  25.632    1.000 
## 2 psum2(x, y, z, na.rm = TRUE)           20 164.476    6.417
## 1  psum(x, y, z, na.rm = TRUE)           20  63.719    2.486

Sven 的版本(可以说是正确的)要慢很多,
尽管它是否重要取决于应用程序。
有人想修改内联/Rcpp 版本吗?

至于为什么它不存在:不知道,但祝你好运让 R-core 做这样的添加......我无法立即想到一个足够普遍的 *misc这可以进入的包......

Matthew 在 r-devel 上的跟进线程在这里(这似乎证实了):
r-devel: There is pmin and pmax each taking na.rm, how about psum?

关于r - 有 pmin 和 pmax 分别取 na.rm,为什么没有 psum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123638/

相关文章:

r - 例如 %+% 做什么?在 R

r - 对分位数回归的系数应用正/负约束

r - 类型为 'envir' 的参数无效 'character' -- 在带有晶格直方图的自定义函数中

r - R data.table 中具有外部指定四分位数断点的四分位数排序器

python - 如何在 Python 中生成 HTML 报告?

r - Mongolite 未将带有列表列的数据框正确插入 Mongodb

r - lm() 如何知道哪些预测变量是分类的?

r - 混合Cor : Misidentification of categorical data for PCA?

r - 无法使用 rgp 执行任何符号回归

r - 如何确定一个点是高于还是低于 R 中连接点的线?