简体   繁体   中英

find median excluding diagonal in R

I'm having trouble with R programming. From a matrix, how can I find the median of each row exclude the diagonal?

Ex: matrix 4x4

0 1 2 3 

1 0 1 2

2 1 0 1

3 2 1 0

I want to find the median of each row excluding the diagonal (in this ex, the diag=0)

I've tried:

diag(A) <- NA
mean(A, na.rm = TRUE) # doesn't work

apply(A, 1, median) # it works but the calculation including the diagonal. 

Try this:

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

I'm not sure why you are using mean() ; why don't you try median() ? Here goes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM