0

My dataset is the following:

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

But I would like to add another column in this dataset. The column name is predicted. The values are like actual, which is given, but predicted is the maximum of the value from column 2:5. Like predicted of row 1 is Product_lifestyle and predicted of row 2 is Product_people

Kindly help me to do it in R

IRTFM
  • 258,963
  • 21
  • 364
  • 487

2 Answers2

1

If I understand the question the following code should do it.

df$predicted <- names(df)[(apply(df[2:6], 1, which.max) + 1)]

However given your example data Product_lifestyle would be the predicted column in both cases.

Dave Ross
  • 673
  • 4
  • 12
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

If it is the column name you are interested in, you could do the following (with base 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
Lennyy
  • 5,932
  • 2
  • 10
  • 23