[英]In R, how to create a new column from the column headings of other columns based on their values
I have a dataframe as below:我有一个 dataframe 如下:
Type Prob_A prob_B prob_C
Vinyl .57 .43 0
Wood .2 .4 .4
Ceramic .12 .80 .08
I need to create a new column called Status.我需要创建一个名为 Status 的新列。 Check the probabilities and get the heading of the max value and call it as A, B or C.
检查概率并获取最大值的标题并将其称为 A、B 或 C。 In my real data asset, I have 10 columns I need to compare.
在我的真实数据资产中,我需要比较 10 列。
We can use max.col
to get the column index of the first max
values and select the substring of the column names我们可以使用
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.