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

How to add "+" to positive values in front in the dataframe?

I have a numerical column with NAs, negative, positive, and 0 values. What I want is the following:

  1. If the value is positive, I want to add "+" in front
  2. If it is Negative, 0, or NA, leave it as it is:

Data:

df <- data.frame (a = c(12,-34,NA,-23,5,0,NA))

Expected outcome:

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

    a
1  +12
2 -34
3  NA
4 -23
5   +5
6   0
7  NA

>Solution :

Another possible solution, based on formatC:

gsub("NA", NA, formatC(df$a, flag = "+0", zero.print = T))

#> [1] "+12" "-34" NA    "-23" "+5"  "0"   NA
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