How to Convert R List to Numeric Value

A list in R is a specific type of vector with the difference that it can store mixed types like numbers, strings, vectors, another list, a matrix, or even a function as its elements. Decimal values are called numerics in R. It is the default computational data type of R. If we assign a decimal value to a variable then it will be of numeric type. If we assign an integer to a variable, it is still being saved as a numeric value.

Convert R List to Numeric Value

To convert R List to Numeric value, use the combination of the unlist() function and as.numeric() function. The unlist() function in R produces a vector that contains all the atomic components. To convert factorial value to numeric value in R, use the as.numeric() function.

Code snippet for converting list to numeric value

as.numeric(unlist(data))

The data is the list consists of vectors.

The first thing we will define is vectors.

rv1 <- 1:5
rv2 <- 6:10

Then use the list() function to create a list from vectors.

rv1 <- 1:5
rv2 <- 6:10

data <- list(rv1, rv2)
data

Output

[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 6 7 8 9 10

Finally, use the unlist() and as.numeric() function to convert a list to a numeric value.

rv1 <- 1:5
rv2 <- 6:10

data <- list(rv1, rv2)

num <- as.numeric(unlist(data))
num

Output

 [1] 1 2 3 4 5 6 7 8 9 10

You can see that the final output is a numeric value, and to check its data type, use the typeof() function.

typeof(num)

It will give us the double as an output that means it’s a numeric value. The numeric data type is identical to double (and real ). It creates a double-precision vector of the specified length with each element equal to 0.

If the values are of type factor, then you should convert them using the following code snippet.

as.numeric(as.character(unlist(data)))

That is it for converting a list to a numeric value in R programming.

See also

R List to Array

R List to data frame

R List to Vector

R List to String

R List to Matrix

Leave a Comment