Consider the following matrix m :
ca bsa rd zaa ada 3 4 3 2 aca 1 4 5 2 ara 3 4 3 2 ava 3 4 5 2
I try to find the minimum value for each row and return data.frame as:
qsd 1 ada zaa 2 2 aca ca 1 3 ara zaa 2 4 ava zaa 2
Now I am doing:
res <- t(sapply(seq(nrow(m)), function(i) { j <- which.min(m[i,]) c(q = rownames(m)[i], s = colnames(m)[j], d = m[i,j])})) res <- data.frame(res) res$d <- as.numeric(res$d)
I am looking for a better way to create this.
It is not possible to build res with c() (forcing all components to the same type), then convert it to data.frame and finally change d to numeric to get the following structure:
'data.frame': 4 obs. of 3 variables: $ q: Factor w/ 4 levels "aca","ada","ara",..: 2 1 3 4 $ s: Factor w/ 2 levels "ca","zaa": 2 1 2 2 $ d: num 2 1 2 2
I will also need to handle a case where there may be several lows
Data
m <- structure(c(3, 1, 3, 3, 4, 4, 4, 4, 3, 5, 3, 5, 2, 2, 2, 2), .Dim = c(4L, 4L), .Dimnames = list(c("ada", "aca", "ara", "ava"), c("ca", "bsa", "rd", "zaa")))