mardi 1 septembre 2020

how to state an ifelse condition that changes column value depending on column names? ( spoiler: what I've tried results in NA)

I'm selecting the top 3 traits represented as numerical values to show a summary of a person's test result. We have a total of 6 traits, from which we select the 3 highest values by sorting by desc criteria in a previuous data frame. So, depending on the values we could have different column-names that identifies the trait that the number refers to, always 3 major traits from a total of 6 traits.

For the numerical representation I already have some charts to show the values. I would like to show a table with some text related to those top 3 traits.

What I'm trying to do is to replace the numerical value for the related text, according to the trait name that occupies the column name, so that way the text matches with the trait on that column.

I'm doing that by writing an if else statement but I don't know how to refer to the column name, so what I've tried until now goes like this:

Lets say that in this case the top 3 traits are the following:

df <- data.frame (Adaptable = 8.1, Dinamic = 7.7, Practic= 4.7)

So I need my code to replace each number for the description of each trait. As the traits are not going to be always presented in the same order, it is necessary to establish the conditions. So I'm trying by now just with the first trait using this code that make some sense for me but at the end, even using the colnames as values when I run the ifelse statement the value in the needed column is replaced by NA.

if (colnames(df[1]) == "Adaptable") {
  df[1,1] = "text for adaptable trait"
} else (df[1,1] = "some other text")

Now using the colnames as independent values:

df <- data.frame (V1 = c(Adaptable, 8.1), V2 = c(Dinamic, 7.7), V3 = c(Practic, 4.7))


if (df[1,1] == "Adaptable") {
  df[2,1] = "some adaptable text"
} else (df[2,1] = "some other text")

With this specific code the value is replaced by NA

Thank you in advance for any comment and help, I appreciate if you guys can provide some answer or refer some documentation.

Aucun commentaire:

Enregistrer un commentaire