R 如何从概率矩阵创建10矩阵

R 如何从概率矩阵创建10矩阵,r,R,我有这样一个概率矩阵: 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 我想把它转换成一个1,0的矩阵,最高概率为1,其余为0: ID V1 V2 V3 V4 1 0 0 1

我有这样一个概率矩阵:

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
我想把它转换成一个1,0的矩阵,最高概率为1,其余为0:

ID  V1     V2         V3        V4
1   0       0          1         0
2.  0       0.         0.        1
3.  0.      0          0         1

如何编写函数来完成任务?

如果是按行,则我们使用
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
数据
df1如果是按行,则我们使用
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
数据
df1我们可以使用
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
#创建df的副本

df2我们可以使用
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
#创建df的副本

df2您的实际数据是否在一个字段(如
0.2.
)中有多个
,或者它们只是像
0.2
这样的数字?您的实际数据是否在一个字段(如
0.2.
)中有多个
,或者它们只是像
0.2
这样的数字?
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))