简体   繁体   English

如何从概率矩阵创建 1 0 矩阵

[英]How to create 1 0 matrix from probability matrix

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:我想将其转换为 1、0 矩阵,最高概率指定为 1,rest 为 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?我如何写一个function来完成任务?

If it is by row, then we get the max value with pmax and do a comparison with the dataset如果是按行,那么我们用pmax得到max并与数据集进行比较

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或与apply

df1[-1] <- t(apply(df1[-1], 1, function(x) +(x == max(x))))

data数据

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))

We can use max.col which returns the index of maximum value in each row.我们可以使用max.col返回每行中最大值的索引。

#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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM