Home > Software design >  How to add " " to positive values in front in the dataframe?
How to add " " to positive values in front in the dataframe?

Time:06-24

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

CodePudding user response:

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

CodePudding user response:

One possibility:

plus <- ifelse(a > 0 & !is.na(a), " ", "")
paste0(plus, a)
#[1] " 12" "-34" "NA"  "-23" " 5"  "0"   "NA" 

Note that after adding " " you get a string not a number.


A more concise way:

sprintf("% d", a)
#[1] " 12" "-34" "NA"  "-23" " 5"  " 0"  "NA" 

sprintf("% d", df$a) does not work. a is float in my original data.

"%d" is for integer. If you have float, use the ifelse method. Although in principle you can use "% f", it might print more decimals than you want.

  • Related