Search code examples
rdataframeif-statementsapply

Conditionally convert strings to a specific numeric value


I'm sure there is an easy answer for this , but I have scanned stack overflow and haven't been able to find a solution. It would seem that potentially a combination of sapply and ifelse functions would do the job (but I'm not sure).

So I have a dataframe with characters, except one column which is a numeric value.

####Create dataframe which needs converting
df <- data.frame(Sample_1 = rep(letters[1:3], each = 3),
             Sample_2 = rep("a", times = 9))
df$Number <- rep(seq(from=1,to=3,by=1))

I would like to convert the characters in this dataframe to a specific number. What the character needs to be converted to depends on the number in the final column. So the criteria would be:

  • If Number = 1, then a should change to 30, b should change to 20 and c should change to 10
  • If Number = 2, then a should change to 35, b should change to 25 and c should change to 15
  • If Number = 3, then a should change to 40, b should change to 30 and c should change to 20

Here is a dataframe highlighting this conversion

A <- c(30,20,10)
B <- c(35,25,15)
C <- c(40,30,20)
Conversion_df <- data.frame(A, B,C)

And here is the desired output.

Final <- data.frame(Sample_1 = c(30,20,10,35,25,15,40,30,20),
                Sample_2 = c(30,20,10,30,20,10,30,20,10))

Thank you in advance for any help.


Solution

  • First we can create a function to valuate the sample with if's statements:

    valuate_sample <- function(x,y) {
        ifelse(y==1, ifelse(x=='a',30, ifelse(x=='b',20, 10)),
               ifelse(y==2, ifelse(x=='a',35, ifelse(x=='b',25, 15)),
                      ifelse(y==3, ifelse(x=='a',40, ifelse(x=='b',30, 20)),0)))
    }
    

    After we just need to use the function in your dataframe:

    df <- df %>% 
        mutate(
            Sample_1 = valuate_sample(Sample_1, Number),
            Sample_2 = valuate_sample(Sample_2, Number)
            )
    

    Result:

    enter image description here