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.

Recent Posts

What is is.factor() Function in R

R consists of various data types, and "factor" is one of them. You can use…

19 hours ago

Efficiently Check If a Vector is Empty in R

The most efficient and idiomatic way to check if a vector is empty in R…

2 days ago

Checking If a Data Frame is Empty in R

What criteria are being evaluated to determine if a data frame is empty? There is…

3 days ago

How to Check If a List is Empty in R

What do we mean when we say an empty list? An empty list does not…

4 days ago

is.element() Function: Check Presence of Elements in R

Whether you want to do membership testing, filter data, identify missing values, check for duplicates,…

5 days ago

as.double() and is.double() Functions in R Language

Whether you want to perform calculations efficiently or derive accurate analysis, you need a double-precision…

1 week ago