你如何找到用于计算r的样本大小



我正在运行变量之间的相关性,其中一些变量缺少数据,因此每个相关性的样本量可能不同。我尝试了print和summary,但这两种方法都不能告诉我每种相关性的n值有多大。这是一个相当简单的问题,我在任何地方都找不到答案。

像这样…?

x <- c(1:100,NA)
length(x)
length(x[!is.na(x)])

你也可以得到这样的自由度…

y <- c(1:100,NA)
x <- c(1:100,NA)
cor.test(x,y)$parameter

但我认为最好是你展示你是如何估计相关性的代码,以获得确切的帮助。

下面是如何在矩阵的列之间查找成对样本大小的示例。如果您希望将其应用于数据框架的(某些)数字列,请相应地组合它们,将结果对象强制转换为矩阵并应用该函数。

# Example matrix:
xx <- rnorm(3000)
# Generate some NAs
vv <- sample(3000, 200)
xx[vv] <- NA
# reshape to a matrix
dd <- matrix(xx, ncol = 3)
# find the number of NAs per column
apply(dd, 2, function(x) sum(is.na(x)))
# tack on some column names
colnames(dd) <- paste0("x", seq(3))
# Function to find the number of pairwise complete observations 
# among all pairs of columns in a matrix. It returns a data frame
# whose first two columns comprise all column pairs
pairwiseN <- function(mat)
{
    u <- if(is.null(colnames(mat))) paste0("x", seq_len(ncol(mat))) else colnames(mat)
    h <- expand.grid(x = u, y = u)
    f <- function(x, y)
           sum(apply(mat[, c(x, y)], 1, function(z) !any(is.na(z))))
    h$n <- mapply(f, h[, 1], h[, 2])
    h
}
# Call it
pairwiseN(dd)

功能易于改进;例如,您可以设置h <- expand.grid(x = u[-1], y = u[-length(u)])以减少计算次数,您可以返回n x n矩阵而不是三列数据帧,等等。

这是Dennis上面函数的for循环实现,输出一个n x n矩阵,而不是必须使用pivot_wide()结果。在我的数据块集群上,它将1865行x 69列矩阵的计算时间从2.5 - 3分钟减少到30-40秒。

谢谢你的回答,丹尼斯,这对我的工作很有帮助。

pairwise_nxn <- function(mat)
{
    cols <- if(is.null(colnames(mat))) paste0("x", seq_len(ncol(mat))) else colnames(mat)
    nn <- data.frame(matrix(nrow = length(cols), ncol = length(cols)))
    rownames(nn) <- colnames(nn) <- cols
    f <- function(x, y)
           sum(apply(mat[, c(x, y)], 1, function(z) !any(is.na(z))))
    for (i in 1:nrow(nn))
      for (j in 1:ncol(nn))
        nn[i,j] <- f(rownames(nn)[i], colnames(nn)[j])
    nn
}  

如果你的变量是命名为ab的向量,会像sum(is.na(a) | is.na(b))这样的东西帮助你吗?

最新更新