我在使用R编程时遇到了麻烦。从矩阵中,我怎样才能找到每行的中位数而不是对角线?
Ex:矩阵4x4
0 1 2 3
1 0 1 2
2 1 0 1
3 2 1 0
我想找到除对角线以外的每一行的中位数(在此例中,diag = 0)
我试过了:
diag(A) <- NA
mean(A, na.rm = TRUE) # doesn't work
apply(A, 1, median) # it works but the calculation including the diagonal.
答案 0 :(得分:2)
试试这个:
A <- matrix(c(0,1,2,3,1,0,1,2,2,1,0,1,3,2,1,0),nrow=4)
sapply(1:4, function(x) median(A[x,-x]))
[1] 2 1 1 2
答案 1 :(得分:1)
我不确定你使用mean()
的原因;你为什么不试试median()
?这是:
A <- read.table(text="0 1 2 3
1 0 1 2
2 1 0 1
3 2 1 0", header=F)
A <- as.matrix(A)
diag(A) <- NA
A
V1 V2 V3 V4
[1,] NA 1 2 3
[2,] 1 NA 1 2
[3,] 2 1 NA 1
[4,] 3 2 1 NA
myFun <- function(x){ median(x, na.rm=T)}
apply(A, 1, FUN=myFun)
[1] 2 1 1 2