我有一个概率矩阵,看起来是这样的:
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如何编写函数来完成任务?
发布于 2020-09-02 22:18:20
如果是按行计算,则使用pmax获取pmax值,并与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或使用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))发布于 2020-09-03 00:23:37
我们可以使用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 <- 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))https://stackoverflow.com/questions/63714232
复制相似问题