如何在R中使用循环统计矩阵行列及行对的固定值出现频率
R语言循环实现矩阵指定规则统计
基础数据定义
示例矩阵:A = matrix(c(0,1,2,1,2,0,2,0,1),3,3)
矩阵共N=3行,n=3列。
统计规则说明
Ro为数值1在每行的出现次数,R1 = n-Ro为每行非1数值的数量- 统计四类固定值对,在任意两行不同列中的共现次数:
- R11对应值对:(1,1)
- Ro1对应值对:(0,1)、(1,0)、(1,2)、(2,1)
- Roo对应值对:(0,0)、(2,2)
- Ro2对应值对:(0,2)、(2,0)
纯循环实现代码
# 1. 初始化基础数据 A <- matrix(c(0,1,2,1,2,0,2,0,1), 3, 3) N <- nrow(A) n <- ncol(A) # 2. 统计每行Ro、R1 Ro <- integer(N) R1 <- integer(N) for (i in 1:N) { Ro[i] <- sum(A[i, ] == 1) R1[i] <- n - Ro[i] } # 可直接打印Ro、R1查看结果:print(Ro); print(R1) # 3. 统计四类值对的跨行列共现次数 count_R11 <- 0 count_Ro1 <- 0 count_Roo <- 0 count_Ro2 <- 0 # 遍历所有两两行组合(i<j避免重复统计同一行对) for (i in 1:(N-1)) { for (j in (i+1):N) { # 遍历所有不同列组合 for (k in 1:n) { for (l in 1:n) { if (k == l) next # 跳过同列场景 current_pair <- c(A[i, k], A[j, l]) # 匹配对应类别计数 if (identical(current_pair, c(1,1))) { count_R11 <- count_R11 + 1 } else if (list(current_pair) %in% list(c(0,1), c(1,0), c(1,2), c(2,1))) { count_Ro1 <- count_Ro1 + 1 } else if (list(current_pair) %in% list(c(0,0), c(2,2))) { count_Roo <- count_Roo + 1 } else if (list(current_pair) %in% list(c(0,2), c(2,0))) { count_Ro2 <- count_Ro2 + 1 } } } } } # 打印统计结果 cat("R11计数:", count_R11, "\n") cat("Ro1计数:", count_Ro1, "\n") cat("Roo计数:", count_Roo, "\n") cat("Ro2计数:", count_Ro2, "\n")
结果查看
运行代码后可直接输出所有统计项的结果。
内容的提问来源于stack exchange,提问作者Daraz
相关产品推荐
相关产品推荐

