In this square matrix I want to look up all non-zero values in the first column and delete the columns that corresponds to the row names of the non-zero values. Then I want to look up the next not deleted column and repeat the same process, and repeat this till I reached the last column. Any advice?
Matrix example
added an example that is not a picture
newt <- matrix(c(0,1,0,0,1,0,0,1,0,0,0,1,0,1,0,1), nrow = 4, ncol = 4)
colnames(newt) <- c("1", "2", "3", "4")
only columns 1 and 3 should be retained
You can take help of this while
loop:
rowname <- rownames(newt)
vec <- colnames(newt)
i <- 1
col <- vec[i]
while(i < length(vec)) {
vec <- setdiff(vec, rowname[newt[, col] == 1])
i <- i + 1
col <- vec[i]
}
result <- newt[, vec]
result
# 1 3
#1 0 0
#2 1 0
#3 0 0
#4 0 1
data
newt <- matrix(c(0,1,0,0,1,0,0,1,0,0,0,1,0,1,0,1), nrow = 4, ncol = 4)
colnames(newt) <- c("1", "2", "3", "4")
rownames(newt) <- c("1", "2", "3", "4")
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.