Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

1 Answers

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
like image 66
PaulS Avatar answered Oct 21 '25 03:10

PaulS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!