I am trying to convert from a string to a double in R. However, every time I convert the number, R creates an integer.
For example:
a = "100.11"
a = as.double(a)
And the output reads 100
. How to I retain the decimals when converting from string to numeric?
I've set options(digits=3)
.
Thanks
Mike
To convert String to Integer in R programming, call strtoi() function, pass the string and base values to this function. strtoi(string, base) returns the integer value of the given string with respect to the specified base.
The C library function double strtod(const char *str, char **endptr) converts the string pointed to by the argument str to a floating-point number (type double). If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.
To convert elements of a Vector to Strings in R, use the toString() function. The toString() is an inbuilt R function used to produce a single character string describing an R object.
You can change data types using as. * where * is the datatype to change to, the other way is using class(). class(df$var) = "Numeric".
The problem is the option you have set:
options(digits=3)
as.double("100.11")
#[1] 100
options(digits=5)
as.double("100.11")
#[1] 100.11
digits
"controls the number of digits to print when printing numeric values". You set the option to 3 and are shown 3 digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With