Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Converting from string to double

Tags:

string

r

double

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

like image 928
Mike Avatar asked Nov 04 '14 12:11

Mike


People also ask

How do I convert string to numeric in R?

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.

How do you turn a char into a double?

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.

How do I cast a string in R?

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.

How do I change datatype of a variable in R?

You can change data types using as. * where * is the datatype to change to, the other way is using class(). class(df$var) = "Numeric".


1 Answers

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.

like image 200
Roland Avatar answered Oct 10 '22 16:10

Roland