jeudi 14 février 2019

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.

Aucun commentaire:

Enregistrer un commentaire