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() returns a numeric value or converts any value to a numeric value.

Syntax

as.numeric(unlist(data))

Parameters

Argument Description
data It represents the list consisting of vectors.

Example

Here are the two vectors.

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

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

colMeans(): Calculating the Mean of Columns in R Data Frame

The colMeans() function in R calculates the arithmetic mean of columns in a numeric matrix,…

3 days ago

rowMeans(): Calculating the Mean of rows of a Data Frame in R

The rowMeans() is a built-in, highly vectorized function in R that computes the arithmetic mean…

6 days ago

colSums(): Calculating the Sum of Columns of a Data Frame in R

The colSums() function in R calculates the sums of columns for numeric matrices, data frames,…

2 weeks ago

rowSums(): Calculating the Sum of Rows of a Matrix or Data Frame in R

The rowSums() function calculates the sum of values in each numeric row of a matrix,…

2 weeks ago

R View() Function

The View() is a utility function in R that invokes a more intuitive spreadsheet-style data…

3 weeks ago

summary() Function: Producing Summary Statistics in R

The summary() is a generic function that produces the summary statistics for various R objects,…

4 weeks ago