2017-10-13 152 views
0

我有一些空行和空列的矩陣。我想將空行和列全部移動到右側和底部矩陣的末端。如何將特定行移動到R中矩陣的末尾?

我設法獲得所有空行的rownames和列名。

什麼,我試圖做的:

  1. 做一個for循環,刪除掉基於索引的所有行和列(因爲空行更改後的每個順序刪除不工作,所以我放棄了這個想法)
  2. 根據行名稱的屬性刪除行。

Cnew = Cnew[!(Cnew$rownames %in% empty_rownames)]

似乎無法得到它的工作雖然...

回答

0

假設您有一個6x6矩陣,其中一個空列和一個空行(意味着它們的所有條目都是NA

Cnew <- matrix(nrow = 6, ncol = 6, data = 1) 

Cnew[,4] <- NA 
Cnew[3,] <- NA 

empty.columns <- which(colSums(Cnew, na.rm = TRUE) == 0) 
empty.rows <- which(rowSums(Cnew, na.rm = TRUE) == 0) 

# we first delete the row and cols 

# for deleting do 
Cdel <- Cnew[-empty.rows,-empty.columns] 

# and then paste the rows and cols at the edges again 
Cdel <- cbind(Cdel, rep(NA, length(empty.columns))) 
Cdel <- rbind(Cdel, rep(NA, length(empty.rows))) 
0

如果只是爲了刪除行(觀察)與NA值在一些列的

test <-matrix( 
    c(rep(c(NA, 1:9), 8) ), 
    nrow=10, 
    ncol=8) 
test <- test[complete.cases(test),] 
相關問題