![](/img/trans.png)
[英]Looking for a way to plot a pairwise scatterplot matrix where variables are in two groups
[英]What is the easiest way to find the pairwise complete data for two variables?
假设您有两个都有一些缺失数据的变量,但是这些缺失数据可能不会完全重叠。 查找没有丢失值的公共数据点数量的最简单方法是什么? 有内置功能吗?
一种方法是使函数如下所示:
pairwise.miss = function(x, y) {
#deal with input types
x = as.vector(x)
y = as.vector(y)
#make combined object
c = cbind(x, y)
#remove NA rows
c = c[complete.cases(c), ]
#return length
return(nrow(c))
}
另一个想法是使用一些返回成对完整数据的函数。 例如,来自Hmisc
rcorr()
执行此操作,但是可能会给非数字数据带来错误。 所以:
rcorr(x, y)$n[1,2]
有更容易的方法吗?
您可以简单地在complete.cases()
和sum()
输出中列出两个变量。
x <- c(1, 2, 3, NA, NA, NA, 5)
y <- c(1, NA, 3, NA, 3, 2, NA)
complete.cases(x, y)
#[1] TRUE FALSE TRUE FALSE FALSE FALSE FALSE
sum(complete.cases(x, y))
#[1] 2
逻辑向量的总和为TRUE
元素的数量,因为TRUE
强制为1,而FALSE
强制为0。
这适用于任何数据类型。 但是,请注意,空字符串(即""
)不被视为丢失。 实际的缺失字符值由NA_character_
表示。
一种可能的解决方案是使用is.na
和逻辑运算符:
!(is.na(x) | is.na(y)) # logical vector
which(!(is.na(x) | is.na(y))) # integer vector of indices.
如果只需要总数,请使用:
sum(!(is.na(x) | is.na(y)))
我对以上给出的解决方案进行了基准测试:
if (!require("pacman")) install.packages("pacman")
pacman::p_load(microbenchmark)
#fetch some data
x = iris[1] #from isis
y = iris[1]
x[sample(1:150, 50), ] = NA #random subset
y[sample(1:150, 50), ] = NA
#benchmark
times = microbenchmark(pairwise.function = pairwise.miss(x, y),
sum.is.na = sum(!is.na(x) & !is.na(y)),
sum.is.na2 = sum(!(is.na(x) | is.na(y))),
sum.complete.cases = sum(complete.cases(x, y)));times
结果:
> times
Unit: microseconds
expr min lq mean median uq max neval
pairwise.function 202.205 217.2935 244.31481 233.3150 253.8460 450.763 100
sum.is.na 75.594 78.5500 89.26383 80.5730 94.1035 248.558 100
sum.is.na2 74.662 77.6170 89.23899 80.5725 94.8825 167.676 100
sum.complete.cases 14.311 16.1770 18.77197 17.1105 17.7330 155.233 100
因此,与sum.complete.cases一种方法相比,我的原始方法非常慢。
也许在这种计算中很少需要速度,但是在同样易于使用的情况下,最好还是使用最有效的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.