How can I insert a decimal separator "." after two digit in a specif column in R?

Viewed 21

I have a data.frame with two column in which there are numbers in the following format:

Latitude Longitude

-300663 -512344

enter image description here

I wish insert a "." after two digits to convert to a decimal number, like:

Latitude Longitude

-30.0663 -51.2344

enter image description here

How can I do this?

1 Answers

As someone above already noted, you can simply scale the variable by dividing it by whatever number you choose. Just wanted to add that if you are only looking to explicitly turn something from an integer into a decimal format, you can also use format, like so:

x <- 40000
formatted.x <- format(x,
       nsmall = 4) # how many digits after the decimal
formatted.x

Which gives you what you want:

[1] "40000.0000"

However, if you check the class of the variable saved:

class(formatted.x)

You will find it is formatted to be a character variable, which can be annoying if you try to treat it like a decimal. Another option if you want all numbers in R to have more/less decimals is to manually change the options in R.

options(scipen=1000) # changes scientific notation
options(digits=5) # changes number of digits

Generally speaking, I wouldn't advise doing either of these for your specific purpose, but figured I would note these as other ways this can be achieved.

Related