How to coerce a list object to type 'double'

前端 未结 5 605
执笔经年
执笔经年 2020-12-02 06:13

The code:

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


        
相关标签:
5条回答
  • 2020-12-02 06:55

    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]])

    0 讨论(0)
  • 2020-12-02 07:02

    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]}
    
    0 讨论(0)
  • 2020-12-02 07:07

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

    0 讨论(0)
  • 2020-12-02 07:10

    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)))
    }
    
    0 讨论(0)
  • 2020-12-02 07:16

    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.

    0 讨论(0)
提交回复
热议问题