How to coerce a list object to type 'double'

R

R Problem Overview


The code:

a <- structure(list(`X$Days` = c("10", "38", "66", "101", "129", "185", "283", 
                                 "374")), .Names = "X$Days")

Then a is like

$`X$Days`
[1] "10"  "38"  "66"  "101" "129" "185" "283" "374"

I would like to coerce a to an array of numeric values, but coercing functions return me

Error: (list) object cannot be coerced to type 'double'

Thanks,

R Solutions


Solution 1 - R

If you want to convert all elements of a to a single numeric vector and length(a) is greater than 1 (OK, even if it is of length 1), you could unlist the object first and then convert.

as.numeric(unlist(a))
# [1]  10  38  66 101 129 185 283 374

Bear in mind that there aren't any quality controls here. Also, X$Days a mighty odd name.

Solution 2 - R

If your list as multiple elements that need to be converted to numeric, you can achieve this with lapply(a, as.numeric).

Solution 3 - R

You can also use list subsetting to select the element you want to convert. It would be useful if your list had more than 1 element.

as.numeric(a[[1]])

Solution 4 - R

In this case a loop will also do the job (and is usually sufficiently fast).

a <- array(0, dim=dim(X))
for (i in 1:ncol(X)) {a[,i] <- X[,i]}

Solution 5 - R

There are problems with some data. Consider:

as.double(as.character("2.e")) # This results in 2

Another solution:

get_numbers <- function(X) {
    X[toupper(X) != tolower(X)] <- NA
    return(as.double(as.character(X)))
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLisa AnnView Question on Stackoverflow
Solution 1 - RBenBarnesView Answer on Stackoverflow
Solution 2 - RMatthew PlourdeView Answer on Stackoverflow
Solution 3 - RUSER_1View Answer on Stackoverflow
Solution 4 - RKarsten ReussView Answer on Stackoverflow
Solution 5 - Ruser5274471View Answer on Stackoverflow