0

I have a column in a data frame in R that looks like this:

10.01 10.04 10.08 9.99 9.95 9.98 9.1

I need all of the numbers to have the same number of digits by adding zeros to the beginning or the end but only if there are less than 5 characters (two numbers in each side of the decimal point):

10.01 10.04 10.08 09.99 09.95 09.98 09.10

how can I do it in R? thank you

Progman
  • 16,827
  • 6
  • 33
  • 48

1 Answers1

0

You could try sprintf(). Based on the documentation, in the pattern "%05.2f", % is the start of the specification; 0 means padding with leading zero; 5 is the total length of the output including the decimal; 2 means the decimal number allowed; f means it is a decimal number. The output is a character vector.

x <- c(10.01, 10.04, 10.08, 9.99, 9.95, 9.98, 9.1)
sprintf("%05.2f", x)

# [1] "10.01" "10.04" "10.08" "09.99" "09.95" "09.98" "09.10"
Zaw
  • 1,434
  • 7
  • 15
  • Thank you for your reply I tried it but got this message error: Error in sprintf("%05.2f", Formula$Lat) : invalid format '%05.2f'; use format %s for character objects – Yaly Mevorach Jun 06 '21 at 09:25
  • Is `Formula$Lat` a character? If so, perhaps you can convert it to numeric before using `sprintf()`. Something like `sprintf("%05.2f", as.numeric(Formula$Lat))`. – Zaw Jun 06 '21 at 09:31
  • your values are probably saved as characters and not as numeric or integer. `as.numeric(variable_values)` should fix it – CroatiaHR Jun 06 '21 at 09:32