[英]In R, how to create a new column from the column headings of other columns based on their values
我有一个 dataframe 如下:
Type Prob_A prob_B prob_C
Vinyl .57 .43 0
Wood .2 .4 .4
Ceramic .12 .80 .08
我需要创建一个名为 Status 的新列。 检查概率并获取最大值的标题并将其称为 A、B 或 C。 在我的真实数据资产中,我需要比较 10 列。
我们可以使用max.col
来获取第一个max
的列索引和列名的 select 和 substring
df1$Status <- substring(names(df1)[-1],
nchar(names(df1)[-1]))[max.col(df1[-1], 'first')]
df1$Status
#[1] "A" "B" "B"
df1 <- structure(list(Type = c("Vinyl", "Wood", "Ceramic"), Prob_A = c(0.57,
0.2, 0.12), prob_B = c(0.43, 0.4, 0.8), prob_C = c(0, 0.4, 0.08
)), class = "data.frame", row.names = c(NA, -3L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.