lundi 27 janvier 2020

R Data Frames - Assigning a Text Value Based on Adjacent Columns Values

I am very new to R and I am trying to do something that I can only imagine is very simple, but I can't seem to get it to work.

I am trying to add a new column which will say: "First Quartile", "Second Quartile" etc., based on the already populated quartile values in the data frame. I thought this would a simple if else statement job, but my below code populates the new column with "Fourth Quartile" only, and "No Value" for when there is an NA in the column which the output is based off.

My code is:

Quartile_Apply <- function(row) { 
  One_Y_return <- row[10]

  if (is.na(One_Y_return)) {
    return("No Value")
  }

    if (One_Y_return <= 25 & One_Y_return > 0) {
      return("First Quartile")
    } else if (One_Y_return <= 50 & One_Y_return > 25) {
      return("Second Quartile")
    } else if (One_Y_return <= 75 & One_Y_return >50) {
      return("Third Quartile" )
    } else {
      return("Fourth Quartile")
    }
  }

df_Fund_Fee_Data$`1Y_Perf_Quartile` <- apply(df_Fund_Fee_Data, 1, Quartile_Apply)

View(df_Fund_Fee_Data)

The row[10] part is aimed to point the if statements to the "1Y_Return_Percentile" column, which the quartiles will be based off, i.e. the column is column number 10, and then apply to all rows in the data frame.

I feel like this shouldn't be so complicated, and I might be missing something glaringly obvious, but I haven't been able to get it to work! I have also tried a bunch of different adaptations of the code, so I have just attached my current state of work.

Many thanks in advance, Harry

Aucun commentaire:

Enregistrer un commentaire