Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to coerce a list object to type 'double'

Tags:

r

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,

like image 615
Lisa Ann Avatar asked Sep 12 '12 08:09

Lisa Ann


4 Answers

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.

like image 117
BenBarnes Avatar answered Nov 20 '22 05:11

BenBarnes


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

like image 42
Matthew Plourde Avatar answered Nov 20 '22 07:11

Matthew Plourde


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

like image 9
USER_1 Avatar answered Nov 20 '22 05:11

USER_1


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]}
like image 2
Karsten Reuss Avatar answered Nov 20 '22 06:11

Karsten Reuss