0

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.

Daniel Muñoz
  • 547
  • 1
  • 7
  • 23
Luiy_coder
  • 321
  • 2
  • 11
  • Have a look at `ifelse()`. `if` only accepts length-one logical vector, while `ifelse` is vectorized. – Ape Aug 23 '19 at 07:51
  • Can you share `df` using `dput(df)` please? See https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Chelmy88 Aug 23 '19 at 08:30

1 Answers1

0

Assuming your data.frame is called "df" and your columns "rank" and "functional level" have the indexes i and j respectively, I would run an apply() loop over you data.frame

df$new.column <- apply(df, 1, function(x){paste0(x[i], gsub("f","", x[j]))}

This pastes the columns together and gsub() removes the "f" from the second column before pasting.

Sbamo
  • 51
  • 4