I have a 100 x 100 matrix that has 1800 missing values represented by NaN
. I have another 1800 x 1 matrix that contains all these missing values. I want to plug in these values from my 1800 x 1 matrix to the first matrix.
I tried;
data_matrix[is.na(data_matrix)] <- predicted_values[1,]
But this did not work.
Perhaps the safest option would be to do it based on row/col names? Because both of my matrices have corresponding row/col names. Here's an example of what I mean:
data_matrix
VAL.T VAL.U VAL.V VAL.W
A 10.5 NaN 203 902
B 20.9 343 12 NaN
C 32 22 NaN 90
D 12 NaN NaN 23.1
predicted_values
VAL.U:A 65
VAL.W:B 21
VAL.V:C 23.9
VAL.U:D 11.1
VAL.V:D 78
The order that values are arranged in predicted_values might also be helpful: ie values in predicted_values are arranged in a way as if we're moving from the beginning of first row in data_matrix to the end of first_row and then moving to next row. This is the way NaN values should be replaced.
Since predicted_values
stores the values by row then column, while matrices normally store their values column-wise, you should do transposition.
a=t(data_matrix)
a[is.na(a)]=predicted_values[,1]
data_matrix=t(a)
Use a two-column matrix built from splitting the first predval column as the first (single) argument to "[<-" and predval's second column as the second argument:
idxm <- cbind( sapply( strsplit(as.character(predval$V1), ":"), "[",2),
sapply( strsplit(as.character(predval$V1), ":"), "[",1) )
dtm[ idxm ] <- predval$V2
dtm
#-----------
VAL.T VAL.U VAL.V VAL.W
A 10.5 65.0 203.0 902.0
B 20.9 343.0 12.0 21.0
C 32.0 22.0 23.9 90.0
D 12.0 11.1 78.0 23.1
dput(predval)
structure(list(V1 = structure(c(1L, 5L, 3L, 2L, 4L), .Label = c("VAL.U:A",
"VAL.U:D", "VAL.V:C", "VAL.V:D", "VAL.W:B"), class = "factor"),
V2 = c(65, 21, 23.9, 11.1, 78)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-5L))
dput(dtm)
structure(c(10.5, 20.9, 32, 12, 65, 343, 22, 11.1, 203, 12, 23.9,
78, 902, 21, 90, 23.1), .Dim = c(4L, 4L), .Dimnames = list(c("A",
"B", "C", "D"), c("VAL.T", "VAL.U", "VAL.V", "VAL.W")))
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.