R Basic

How to Convert List to Numeric in R

To convert a list to a numeric value in R, you can combine the unlist() function and the as.numeric() function.

The “unlist()” function produces a vector that contains all the atomic components and the as.numeric() function returns a numeric value or converts any value to a numeric value.

Syntax

as.numeric(unlist(data))

Parameters

data: It is the data is the list consisting of vectors.

Example

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

Then, use the list() function to create a vector list.

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() functions.

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, meaning 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, you should convert them using the following code snippet.

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

That’s it.

Share
Published by
Krunal Lathiya

Recent Posts

How to Use “lwd” in R

The lwd in R is used to specify the width of plot lines. It is…

1 year ago

How to Convert Double to Integer in R

To convert a double or float to an integer, you can use the "as.integer()" function.…

1 year ago

R dirname() Function

The dirname() function in R is used to extract the path to the directory from…

1 year ago

R month.abb

The month.abb is a built-in R constant, a three-letter abbreviation for the English month names. Example 1:…

1 year ago

R seq_along() Function

The seq_along() function in R is used to generate a sequence of integers along the…

1 year ago

Pi in R: Built-in Constants

Pi is a built-in R constant whose value is 3.141593. Pi is the ratio of…

1 year ago