Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

switch elements between columns based on the value of another column r

I have a data frame like this:

D <- data.frame(V1=c(1,2,3,4), V2=c(6,7,8,9), V3=c(3,4,5,6), sign=c("+", "-", "-", "+"))

If the character in column "sign" is "-", I would like to switch values in columns V1 and V2

My desired output would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

          V1 V2 V3 sign
        1  1  6  3    +
        2  7  2  4    -
        3  8  3  5    -
        4  4  9  6    +

I have tried for loops and if and else statements, but it is not working. Could you please tell me how I could achieve this?

>Solution :

Use mapply to loop through the 3 columns at once and assign the result to columns V1 and V2.

D <- data.frame(V1=c(1,2,3,4), V2=c(6,7,8,9), V3=c(3,4,5,6), sign=c("+", "-", "-", "+"))

D[c("V1", "V2")] <- t(mapply(\(x, y, s){
  if(s == "-") c(y, x) else c(x, y)
}, D$V1, D$V2, D$sign))
D
#>   V1 V2 V3 sign
#> 1  1  6  3    +
#> 2  7  2  4    -
#> 3  8  3  5    -
#> 4  4  9  6    +

Created on 2022-03-18 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading