Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to integer or double in R

Tags:

list

r

vector

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.

like image 249
Thomas Avatar asked Sep 28 '10 15:09

Thomas


People also ask

How do I turn a list into an integer in R?

To convert R List to Numeric value, use the combination of the unlist() function and as. numeric() function. The unlist() function in R produces a vector that contains all the atomic components.

What is the difference between integer and double in R?

integer : an integer (positive or negative). Many R programmers do not use this mode since every integer value can be represented as a double . double : a real number stored in “double-precision floatint point format.”

What is double () in R?

double R function converts an integer to the double class. The is. double R function tests whether a data object has the double class.

How do I convert a list to characters in R?

toString() in R To convert the list to string in R, use the toString() function. The toString() is an inbuilt R function that converts An R Object To a Character String.


2 Answers

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
like image 159
Joris Meys Avatar answered Oct 19 '22 13:10

Joris Meys


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
> 
like image 37
Dirk Eddelbuettel Avatar answered Oct 19 '22 13:10

Dirk Eddelbuettel