How to Convert String to Float in R Language

All R platforms must work with values conforming to the IEC 60559 standard. The double is the name of the type in R. The numeric is the name of the mode and the implicit class.

Convert String to Float in R

To convert from a string to a double in R, use the as.double() method. The as.double() method is used to create, coerce to, or test for a double-precision vector. The as.double() function converts an integer to the double class. To check if the input is double or float, use the is.double() function.

Syntax

double(length = 0)
as.double(x, …)
is.double(x)

Parameters

  1. length: It is a non-negative integer specifying the desired length. Double values will be coerced to an integer: supplying an argument of length other than one is an error.
  2. x: It is an object to be coerced or tested.
  3. …: further arguments passed to or from other methods.

The double() method creates a double-precision vector of the defined length. The as.double() is an inbuilt R generic function. It is identical to as.numeric() method. Methods should return an object of base type “double“. The is.double() function tests the double type.

Example

Create a character vector and use the as.double() function to convert character to string. We will use is.character() function to test the double value.

data <- "19.21"
data
typeof(data)
double_data <- as.double(data)
double_data
typeof(double_data)

Output

[1] "19.21"
[1] "character"
[1] 19.21
[1] "double"

As you can see from the output that we converted a string to a double value.

Convert Numeric/Integer to double in R

To convert an integer or numeric value to double, use the as.double() function. To test a double value, use the is.double() function.

data <- 1:5
data
typeof(data)
double_data <- as.double(data)
double_data
typeof(double_data)

Output

[1] 1 2 3 4 5
[1] "integer"
[1] 1 2 3 4 5
[1] "double"

You can see that as.double() method converted an integer value to float or double value.

Conclusion

To convert numeric, integer, string, or character vector to double or float value in R, use the as.double() method. That is it for this tutorial.

See also

R character to numeric

R list to numeric

Add vectors in R

Leave a Comment