In the following example, how do I ask the R to select more than one index if there is a tie (For example in row 3 the minimum is 2 which occurs for both x and y columns. However, sapply
gives the index for x column only) (My apologizes if this looks like a naive question)
df1< -structure(list(x = c(5, 2, 3), y = c(4, 3, 3)), .Names = c("x",
"y"), row.names = c(NA, -3L), class = "data.frame")
df1
x y
1 5 4
2 2 3
3 3 3
sapply(as.list(rownames(df1)),function(x) which.min(df1[x,]))
y x x
2 1 1
just change which.min(df1[x,])
to which(df1[x,]==min(df1[x,]))
. You can even shorten your code by using apply
instead of sapply
> apply(df1, 1, function(x) which(x==min(x)))
[[1]]
y
2
[[2]]
x
1
[[3]]
x y
1 2