Home > Mobile >  Transform dummy matrix into label vector
Transform dummy matrix into label vector

Time:11-06

I'm trying to create a confusion matrix, in order to build it I need to convert this matrix of predictions from my model into a label vector. (to compare it with the vector of actual labels)

Matrix:

    Africa America CentralAsiaSiberia EastAsia Oceania SouthAsia WestEurasia
196      1       0                  0        0       0         0           0
203      0       1                  0        0       0         0           0
239      0       0                  0        1       0         0           0
240      0       0                  0        1       0         0           0
252      0       0                  0        0       0         0           1
253      0       0                  0        0       0         1           0

Vector:

Africa
America
EastAsia
EastAsia
WestEurasia
SouthAsia

I could iterate through all rows using a for loop in order to get the colname associated with the value in row which is equal to 1, but I wonder if there is a simpler way in R to do this.

Thanks!

CodePudding user response:

You can use max.col:

names(df)[max.col(df)]
#[1] "Africa"      "America"     "EastAsia"    "EastAsia"    "WestEurasia" "SouthAsia"  

CodePudding user response:

Here are a could options:

library(tidyverse)

#option 1
df |>
  pivot_longer(everything()) |>
  filter(value == 1)  |>
  pull(name)
#> [1] "Africa"      "America"     "EastAsia"    "EastAsia"    "WestEurasia"
#> [6] "SouthAsia"


#option 2
apply(df, 1, \(x) colnames(df)[(which(x == 1))])
#> [1] "Africa"      "America"     "EastAsia"    "EastAsia"    "WestEurasia"
#> [6] "SouthAsia"
  • Related