Search code examples
rmatrixdplyrrpart

Transform dummy matrix into label vector


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!


Solution

  • You can use max.col:

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