我的数据集如下:
Image Product_lifestyle Product_people Product_text Product_front Product_top Actual
Image_001 0.4 0.1 0.15 0.15 0.1 Product_lifestyle
Image_002 0.35 0.34 0.05 0.21 0.05 Product_people
但是我想在此数据集中添加另一列。列名称为predicted
。给出的值类似于actual
,但是predicted
是列2:5中的最大值。
像预测的第1行是Product_lifestyle
并预测第2行为Product_people
请帮助我在R中完成
答案 0 :(得分:1)
如果我理解这个问题,则以下代码可以完成。
df$predicted <- names(df)[(apply(df[2:6], 1, which.max) + 1)]
但是,考虑到您的示例数据,Product_lifestyle将是两种情况下的预测列。
答案 1 :(得分:0)
library(dplyr)
df %>%
rowwise() %>%
mutate(predicted = max(c_across(Product_lifestyle:Product_top)))
Image Product_lifestyle Product_people Product_text Product_front Product_top Actual predicted
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <dbl>
1 Image_001 0.4 0.1 0.15 0.15 0.1 Product_lifestyle 0.4
2 Image_002 0.35 0.34 0.05 0.21 0.05 Product_peopl 0.35
如果这是您感兴趣的列名,则可以执行以下操作(以R为底):
df$predicted <- names(df[2:5])[max.col(df[,2:5])]
Image Product_lifestyle Product_people Product_text Product_front Product_top Actual predicted
1 Image_001 0.40 0.10 0.15 0.15 0.10 Product_lifestyle Product_lifestyle
2 Image_002 0.35 0.34 0.05 0.21 0.05 Product_peopl Product_lifestyle