2017-03-07 80 views
3

我有以下矩陣:子集化矩陣的值與載體(條件)

> matrix <- matrix(c(1,3,4,NA,NA,NA,3,0,4,6,0,NA,2,NA,NA,2,0,1,0,0), nrow=5,ncol=4) 
> n <- matrix(c(1,2,5,6,2),nrow=5,ncol=1) 

正如你可以看到,對於每個行我有

  1. 多個NAS - 數的NA未定義
  2. ONE單個 「0」

我想對於n的值,以子集0。下面的預期輸出。

> output <- matrix(c(1, 3, 4,NA,NA,NA,3,5,4,6,1,NA,2,NA,NA,2,2,1,6,2), nrow=5,ncol=4) 

我曾嘗試以下

subset <- matrix == 0 & !is.na(matrix) 
matrix[subset] <- n 
#does not give intended output, but subset locates the values i want to change 

當我的 「真實」 數據使用我得到以下信息:

警告消息:在M [子集] < - N的:要替換的項目數不是 替換長度的倍數

謝謝

編輯:添加一行到矩陣,因爲我的現實生活中的問題是與不平衡的矩陣。我在這裏使用矩陣而不是DF,因爲我認爲(不確定)對於非常大的數據集,R對於大矩陣而不是數據框的子集更快。

回答

1

我們可以做到這一點使用

out1 <- matrix+n[row(matrix)]*(matrix==0) 
identical(output, out1) 
#[1] TRUE 
+1

謝謝,這在我的「縮放」的例子。正在尋找這個 – Chrisftw

1

看來你想要按行替換值,但子集是按列替換值(也許這不是一個完全徹底的解釋)。換位矩陣將獲得所需的輸出:

matrix <- t(matrix) 
subset <- matrix == 0 & !is.na(matrix) 
matrix[subset] <- n 
matrix <- t(matrix) 

setequal(output, matrix) 
[1] TRUE 
+0

感謝這,它在我提供的例子上工作。我編輯我的問題,因爲我的真實生活數據不是一個平衡矩陣。歡呼你的回覆 – Chrisftw

1

你可以嘗試用ifelse此選項:

ifelse(matrix == 0, c(n) * (matrix == 0), matrix) 

#  [,1] [,2] [,3] [,4] 
#[1,] 1 NA 1 2 
#[2,] 3 NA NA 2 
#[3,] 4 3 5 NA 
#[4,] NA 6 NA 2 

zero = matrix == 0 
identical(ifelse(zero, c(n) * zero, matrix), output) 
# [1] TRUE