0

I'm a newbie to R and I've learnt that a character string like "12.5" can be coerced to a numeric using as.numeric() function, which gives me the following result.

> as.numeric("12.5")
[1] 12.5

But when I try following, the result doesn't contain the fractional part.

> as.numeric("12.0")
[1] 12

is there a way to keep the fractional part in the result...

Thanks in advance...

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Pavithra Gunasekara
  • 3,902
  • 8
  • 36
  • 46

1 Answers1

1

Is it really necessary to print whole numbers that way? If you're worried about how it will appear with other numbers, say in a vector or data frame, not to worry. If you have at least one decimal number in the vector, the whole number will appear as a decimal as well.

> as.numeric(c("12.0", "12.1"))
## [1] 12.0 12.1

> data.frame(x = as.numeric(c("12.0", "12.1")))
##      x
## 1 12.0
## 2 12.1

If it's simply for appearance purposes, there are a few functions that can make 12.0 appear numeric. Keep in mind, however that this does not coerce to numeric, even though it looks like it does.

> noquote("12.0")
## [1] 12.0

> cat("12.0")
## 12.0
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245