6

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

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)

我该怎么做?非常感谢

4

3 回答 3

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> 
于 2012-09-24T13:19:33.363 回答
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有一些多余的代码。

于 2012-09-24T13:16:46.223 回答
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
于 2012-09-24T13:20:04.663 回答