似乎 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/