Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract numeric values from a structure object in R

I need to extract numeric values from a variable which is a structure combined with numeric values and names

structure(c(-1.14332132657709, -1.1433213265771, -1.20580568266868, 
-1.75735158849487, -1.35614113300058), .Names = c("carbon", 
"nanotubes", "potential", "neuron", "cell", "adhesion"))

At the end I would like to have a vector with just this information

c(-1.14332132657709, -1.1433213265771, -1.20580568266868, 
-1.75735158849487, -1.35614113300058)

how can I do it? many thanks

like image 421
Claudio Meo Avatar asked Sep 24 '12 13:09

Claudio Meo


People also ask

How do I extract numbers from a string in R?

In this method to extract numbers from character string vector, the user has to call the gsub() function which is one of the inbuilt function of R language, and pass the pattern for the first occurrence of the number in the given strings and the vector of the string as the parameter of this function and in return, this ...

How do I extract values from a vector in R?

Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.


1 Answers

Both as.numeric() and unname() do this:

R> structure(c(-1.14332132657709, -1.1433213265771, -1.20580568266868,
+              -1.75735158849487, -1.35614113300058, NA),
+            .Names = c("carbon", "nanotubes", "potential", 
+            "neuron", "cell", "adhesion"))
   carbon nanotubes potential    neuron      cell  adhesion 
 -1.14332  -1.14332  -1.20581  -1.75735  -1.35614        NA 
R> foo
   carbon nanotubes potential    neuron      cell  adhesion 
 -1.14332  -1.14332  -1.20581  -1.75735  -1.35614        NA 
R>
R> as.numeric(foo)            ## still my 'default' approach
[1] -1.14332 -1.14332 -1.20581 -1.75735 -1.35614       NA
R>
R> unname(foo)                ## maybe preferable though
[1] -1.14332 -1.14332 -1.20581 -1.75735 -1.35614       NA
R> 
like image 130
Dirk Eddelbuettel Avatar answered Sep 29 '22 07:09

Dirk Eddelbuettel