tags:

views:

65

answers:

2

I have a list of about 1000 single integers. I need to be able to do some mathematical computations, but they're stuck in list or character form. How can I switch them so they're usable?

sample data :

y [[1]] [1] "7" "3" "1" "6" "7" "1" "7" "6" "5" "3" "1" "3" "3" "0" "6" "2" "4" "9" [19] "1" "9" "2" "2" "5" "1" "1" "9" "6" "7" "4" "4" "2" "6" "5" "7" "4" "7" [37] "4" "2" "3" "5" "5" "3" "4" "9" "1" "9" "4" "9" "3" "4" "9" "6" "9" "8" [55] "3" "5" "2" "0" "3" "1" "2" "7" "7" "4" "5" "0" "6" "3" "2" "6" "2" "3" [73] "9" "5" "7" "8" "3" "1" "8" "0" "1" "6" "9" "8" "4" "8" "0" "1" "8" "6" ...

Just the first couple of lines.

+3  A: 

See ?unlist :

> x
[[1]]
[1] "1"

[[2]]
[1] "2"

[[3]]
[1] "3"


> y <- as.numeric(unlist(x))

> y
[1] 1 2 3

If this doesn't solve your problem, please specify what exactly you want to do.


edit : It's even simpler apparently :

> x <- list(as.character(1:3))

> x
[[1]]
[1] "1" "2" "3"


> y <-as.numeric(x[[1]])

> y
[1] 1 2 3
Joris Meys
Nice, the unlist with the as.numeric() worked perfectly. Thanks!!
Regarding the edit: that is a not a list of characters. That is a list with one element; that element happens to be a vector.
Dirk Eddelbuettel
@Dirk I know, but it's the structure as provided by the OP. In fact, I should change my initial code as well to reflect the character nature. - which I did now.
Joris Meys
A: 

Try this -- combining as.numeric() and rbind():

> foo <- list("2", "4", "7")
> foo
[[1]]
[1] "2"

[[2]]
[1] "4"

[[3]]
[1] "7"

> bar <- do.call(rbind, lapply(foo, as.numeric))
> bar
     [,1]
[1,]    2
[2,]    4
[3,]    7
> 
Dirk Eddelbuettel
huh? what's wrong with unlist? do.call seems serious overshoot to me...
Joris Meys
Force of habit...
Dirk Eddelbuettel
@Dirk : lol. I am very happy you have that habit though ;-)
Joris Meys
What about rapply?
aL3xa