jeudi 11 mars 2021

R Adding string to colnames if maximum value of each row is negative

I want to add a column in my dataframe which contains the name of the column of absolute max of each row and add a - if the value is negative. I already know how to find the colname of the absolute max of each row:

Year$MAX <- names(Year)[max.col(abs(Year))]

All I want now is to add a - to those names, if the maximum value is negative.

structure(list(Year_PC1 = c(0.08894241, 0.0974053, 0.31973715, 
0.07872326, 0.11825688, 0.26693977, 0.38819524, 0.57135167), 
    Year_PC2 = c(0.00204647, -0.09659042, -0.28659028, -0.2004155, 
    -0.0087369, 0.09324472, 0.19295139, 0.28848406), Year_PC3 = c(-0.83007229, 
    -0.71032944, -0.54154965, -0.26636061, 0.51721381, 0.53136727, 
    0.3217693, 0.34030246), Year_PC4 = c(0.35526945, 0.42689586, 
    0.35262208, 0.41736156, 0.45505958, 0.38535098, 0.52572592, 
    0.40147004), Year_PC5 = c(-0.10552909, 0.05833399, -0.24412172, 
    -0.27525861, 0.26547298, 0.25128881, 0.22226087, 0.11638842
    ), Year_PC6 = c(0.00249045, -0.13485498, 0.03780119, 0.24958282, 
    -0.11141373, -0.02894633, -0.03219833, -0.09467442), Year_PC7 = c(0.02659417, 
    -0.02836294, 0.06889791, -0.39737906, -0.24853771, 0.28679878, 
    0.26115328, 0.18243498), Year_PC8 = c(-0.22630098, -0.03966049, 
    0.21745252, 0.29118665, 0.30205514, 0.14772134, 0.07806185, 
    0.05443241)), row.names = c(NA, 8L), class = "data.frame")

Aucun commentaire:

Enregistrer un commentaire