vendredi 23 août 2019

R adding a new column and populating it with string values based on multiple condition

I'm writing a code in R to add a new column where the values needs to be populated based on two conditions. The problem is there are two columns "rank" and "functional level". For each rank there are multiple functional levels. For example, if there is a rank 'A' then rank A has functional levels f1,f2,f3. Now I need to populate a column called "combination_of_rank_and_functionallevel" in the following way:

if rank = A and functional_level = f1, then combination_of_rank_and_functionallevel = A1

else if rank = A and functional_level = f2, then combination_of_rank_and_functionallevel = A2

else if rank = B and functional_level = f4, then combination_of_rank_and_functionallevel = B4

so on....

I have written a piece of code in R to carry out this logic. The code gets executed but the new column doesn't get populated with the new value. I'm sharing the code below.

if(df$Rank == "A" & df$Function.level == "F1"){
    df$combination_of_rank_and_FL = "A 1" 
  }else if (df$Rank == "A" & df$Function.level == "F2"){
    df$combination_of_rank_and_FL = "A 2"
  }else if (df$Rank == "A" & df$Function.level == "F3"){
    df$combination_of_rank_and_FL = "A 3"
  }else {
    df$combination_of_rank_and_FL = "To be removed from analysis"
  }
}

So the new column "combination_of_rank_and_FL" should get populated when the condition gets satisfied.

Aucun commentaire:

Enregistrer un commentaire