I have a matrix with nucleotide sequences (containing NAs) in rows as shown here:
n.mat
samp1 <- c("a","c","a",NA,"t","c")
samp2 <- c("a","c","t","t",NA,"a")
samp3 <- c("a","g","g","c","a","c")
samp4 <- c("a","g",NA,"g","g", NA)
samp5<- c(NA, "g","g","g","t","g")
n.mat <- rbind(samp1,samp2,samp3,samp4,samp5)
[,1] [,2] [,3] [,4] [,5] [,6]
samp1 "a" "c" "a" NA "t" "c"
samp2 "a" "c" "t" "t" NA "a"
samp3 "a" "g" "g" "c" "a" "a"
samp4 "a" "g" NA "g" "g" NA
samp5 NA "g" "g" "g" "t" "g"
I also have a data frame with two columns containing the sequence names:
df
df <- data.frame(
X1 = c("samp1", "samp2", "samp3", "samp4", "samp5"),
X2 = c("samp2", "samp5", "samp1", "samp3", "samp2"))
X1 X2
1 samp1 samp2
2 samp2 samp5
3 samp3 samp1
4 samp4 samp3
5 samp5 samp2
I would like to fill the gaps of a row in the matrix with nucleotides/values from another row in the matrix indicated by the df$X2 column in the data frame.
So for example: samp1 in the matrix has an NA in its row in the fourth column. So I would like to take the string in the same column from samp2 (indicated by the data frame in column X2). For samp2 I would like to fill the NA by taking the string from samp5 (indicated by the data frame in column X2).
If there is no NA in the row as it is in samp3, then do nothing.
If there are two NAs in a row (as it is in samp4), then I would like to take both strings from samp3 both columns.
I have tried following code:
replace.na <- function(n.mat,val) {
i <- is.na(n.mat)
j <- which(i)
k <- which(!i)
n.mat[j[j > k[length(k)]]] <- val
n.mat
}
n.mat[,-1] <- t(apply(matrix[,-1],1,replace.na))
But I am not quite sure how to include the df table to replace the NAs.