You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化R语言统计多列组合非空值及指定字符数的矩阵生成流程

R语言简洁高效实现方案

实现思路

  • 借助outer函数批量处理矩阵维度的两两计算,完全替代嵌套for循环
  • 用列表存储A-H的统计结果,避免动态生成变量的冗余操作,调用更便捷

完整代码

# 示例数据(可直接运行)
example<-matrix(NA,40,7)
colnames(example)=c("month1","month2","month3","month4","month5","month6","month7")
example[,1]<-rep(c("A","B","C","D","E","F","G","H",NA),len=40)
example[,2]<-rep(c("A","H",NA,"C","E",NA,"F",NA),len=40)
example[,3]<-rep(c("C","A","C",NA),len=40)
example[,4]<-rep(c(NA,"A","F","H","E",NA),len=40)
example[,5]<-rep(c("A",NA),len=40)
example[,6]<-rep(c("C",NA,NA,"E"),len=40)
example[,7]<-rep(c("C","A",NA,NA,"C",NA,"F",NA),len=40)
example<-as.data.frame(example)
sub<-c("ALL","A","B","C","D","E","F","G","H")

# ----------------------
# 1. 生成ALLtable矩阵
# ----------------------
n_col <- ncol(example)
# 定义两两列共同非空行数统计函数
count_all <- Vectorize(function(i,j) {
  sum(!is.na(example[,i]) & !is.na(example[,j]))
})
ALLtable <- outer(1:n_col, 1:n_col, count_all)
# 给矩阵加行列名
dimnames(ALLtable) <- list(colnames(example), colnames(example))

# ----------------------
# 2. 生成A-H对应的Xtable矩阵
# ----------------------
sub_char <- sub[sub != "ALL"]
res_list <- lapply(sub_char, function(x) {
  count_x <- Vectorize(function(i,j) {
    # 统计第i列等于X时,i、j列共同非空的行数
    sum(example[,i] == x & !is.na(example[,j]), na.rm = TRUE)
  })
  xtab <- outer(1:n_col, 1:n_col, count_x)
  dimnames(xtab) <- list(colnames(example), colnames(example))
  return(xtab)
})
# 给列表命名,可直接通过res_list[["A"]]调取A对应的统计矩阵
names(res_list) <- sub_char

# 可选:如果需要单独生成Atable、Btable...全局变量,运行以下代码即可
# list2env(setNames(res_list, paste0(names(res_list), "table")), envir = .GlobalEnv)

结果说明

  • ALLtable为7×7矩阵,行列名对应月度列名,ALLtable[i,j]即为第i和第j个月度列的共同非空行数
  • res_list为命名列表,res_list[["A"]]到res_list[["H"]]分别对应A到H的统计矩阵,符合需求2的计算规则

内容的提问来源于stack exchange,提问作者D.PARK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:48:02