如何从R中的结构对象中提取数值

时间:2012-09-24 13:09:53

标签: r structure numeric names

我需要从变量中提取数值,该变量是一个结合了数值和名称的结构

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

最后,我想要一个只有这个信息的载体

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

我该怎么办? 非常感谢

3 个答案:

答案 0 :(得分:8)

as.numeric()unname()都这样做:

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> 

答案 1 :(得分:2)

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

as.numeric(myVec)
# [1] -1.143321 -1.143321 -1.205806 -1.757352 -1.356141

或者

names(myVec) <- NULL

修改

原型向量的

unname只是names(obj) <- NULL,带有一些多余的代码。

答案 2 :(得分:2)

unname怎么样?

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

+ + > > unname(myVec)
[1] -1.143321 -1.143321 -1.205806 -1.757352 -1.356141