Reputation: 81
I have a probability matrix that looks like this:
ID V1 V2 V3 V4
1 0.15 0.1 0.5 0.25
2. 0 0.1 0.3. 0.6
3. 0.2. 0.25. 0.2. 0.35
I'd like to convert it to a 1, 0 matrix with the highest probability assigned as 1 and the rest as 0:
ID V1 V2 V3 V4
1 0 0 1 0
2. 0 0. 0. 1
3. 0. 0 0 1
How do I write a function to accomplish the task?
Upvotes: 1
Views: 107
Reputation: 388982
We can use max.col
which returns the index of maximum value in each row.
#Create a copy of df
df2 <- df
#turn all values to 0
df2[-1] <- 0
#Get the max column number in each row and turn those values to 1
df2[cbind(1:nrow(df), max.col(df[-1]) + 1)] <- 1
df2
# ID V1 V2 V3 V4
#1 1 0 0 1 0
#2 2 0 0 0 1
#3 3 0 0 0 1
data
df <- structure(list(ID = 1:3, V1 = c(0.15, 0, 0.2), V2 = c(0.1, 0.1,
0.25), V3 = c(0.5, 0.3, 0.2), V4 = c(0.25, 0.6, 0.35)),
class = "data.frame", row.names = c(NA, -3L))
Upvotes: 1
Reputation: 887108
If it is by row, then we get the max
value with pmax
and do a comparison with the dataset
df1[-1] <- +(df1[-1] == do.call(pmax, df1[-1]))
df1
# ID V1 V2 V3 V4
#1 1 0 0 1 0
#2 2 0 0 0 1
#3 3 0 0 0 1
Or with apply
df1[-1] <- t(apply(df1[-1], 1, function(x) +(x == max(x))))
df1 <- structure(list(ID = c(1, 2, 3), V1 = c("0.15", "0", "0.2."),
V2 = c("0.1", "0.1", "0.25."), V3 = c("0.5", "0.3.", "0.2."
), V4 = c(0.25, 0.6, 0.35)), class = "data.frame",
row.names = c(NA,
-3L))
Upvotes: 4