我目前正在嘗試通過回圈舊矩陣來創建一個新矩陣。我想在新矩陣中更改的是用字符“重新編碼”替換某些值。兩個矩陣都應該有 10 列和 100 行。
在當前情況下,某個值是與 中的一個值匹配的值vector_A。
例如:
for (i in 1:10) {
new_matrix[,i] <- old_matrix[,i]
output_t_or_f <- is.element(new_matrix[,i],unlist(vector_A))
if (any(output_t_or_f, na.rm = FALSE)) {
replace(new_matrix, list = new_matrix[,i], values = "recode")
}
}
所以output_t_or_f應該取值TRUE或FALSE,這取決于 i 是否在 vector_A 中,如果output_t_or_f是TRUE則舊值應替換為字符"recode"
目前new_matrix看起來就像這樣,old_matrix所以我猜 if 陳述句有問題?
不幸的是,我不能真正分享我的資料,但我將一些示例資料放在一起:如果old_matrix看起來像這樣:
> old_matrix
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
和 vector_A 看起來像這樣:
> vector_A
[1] 12 27 30 42 37 9
then the new matrix should looks like this:
new_matrix
[,1] [,2] [,3] [,4] [,5]
[1,] "1" "6" "11" "16" "21"
[2,] "2" "7" "recoding" "17" "22"
[3,] "3" "8" "13" "18" "23"
[4,] "4" "recoding" "14" "19" "24"
[5,] "5" "10" "15" "20" "25"
I am very new to R and can't seem to find the problem. Would appreciate any help!! Thanks :-)
uj5u.com熱心網友回復:
由于每列中的替換都是相同的,因此您不需要回圈。嘗試這個:
new_matrix <- old_matrix
new_matrix[new_matrix %in% vector_A] <- "recode"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/453323.html
標籤:r loops if-statement replace
