【问题标题】:R - extract output into a dataframeR - 将输出提取到数据框中
【发布时间】:2014-08-03 21:58:51
【问题描述】:

我在 R 中运行了统计分析(支持向量机包 e1071),我想将部分输出提取到向量中。 例如:

>library(e1071)
>a<-c(0,0,1,1,1)
>b<-c(2,4,5,5,5)
>c<-c(5,6,7,3,7)
>a<-as.factor(a)
>model<-svm(a~b+c,probabiity=TRUE,method="C-classification") #build a SVM classification model

>b<-c(4,4,5,6,7)
>c<-c(4,6,7,3,7)
>test<-data.frame(b,c) ## test data
>probability<-predict(model,test,probability=TRUE)
>probability 

1 2 3 4 5 
0 0 0 0 0 
attr(,"probabilities")
    0   1
1 0.5 0.5
2 0.5 0.5
3 0.5 0.5
4 0.5 0.5
5 0.5 0.5
Levels: 0 1

我想提取列“1”中的所有数据并将其存储在向量中 我该怎么做?

【问题讨论】:

  • 您当前的输出格式是什么?一个字符串?
  • 我如何检查这个?
  • 您需要将str() 在该对象上的结果提供给我们,尽管您可能没有将其保存到对象中。向我们展示代码。

标签: r output


【解决方案1】:

当您显示完整的控制台输出时,您可以看到您想要的数据存储在一个名为“概率”的“属性”中,您需要使用attr 函数来提取它:

> str(probability)
 Factor w/ 2 levels "0","1": 1 1 1 1 1
 - attr(*, "names")= chr [1:5] "1" "2" "3" "4" ...
 - attr(*, "probabilities")= num [1:5, 1:2] 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5] "1" "2" "3" "4" ...
  .. ..$ : chr [1:2] "0" "1"
> attr(probability, "probabilities")
    0   1
1 0.5 0.5
2 0.5 0.5
3 0.5 0.5
4 0.5 0.5
5 0.5 0.5

由于您只想存储第一列,因此您使用 [ 函数并将 j 参数设置为列的编号(或在这种情况下相同的字符名称)

myvals <- attr(probability, "probabilities")[ , '1']
myvals
  1   2   3   4   5 
0.5 0.5 0.5 0.5 0.5 

【讨论】:

  • 我有同样的问题,但是当我尝试你的解决方案时,我得到了下标超出范围
  • 我的解决方案是针对问题量身定制的。我们无法知道您的问题(7 年后)可能是什么。
【解决方案2】:

使用您提供的数据

df <- structure(list(X0 = c(0.9457661, 0.9394421, 0.9348035, 0.9393719, 
0.9409816, 0.9390066, 0.9391518, 0.9407844), X1 = c(0.05423386, 
0.0605579, 0.06519648, 0.06062806, 0.05901843, 0.06099342, 0.06084821, 
0.05921564)), .Names = c("X0", "X1"), class = "data.frame", row.names = c("3", 
"6", "9", "12", "14", "16", "19", "25"))

vector <- df[,1]

vector
[1] 0.9457661 0.9394421 0.9348035 0.9393719 0.9409816 0.9390066 0.9391518
[8] 0.9407844

【讨论】:

  • 谢谢,但输出实际上很长,超过 2000 行。我能以某种方式自动提取数据吗?
  • 一种快速的方法是将[,1] 附加到predict(model, test, probability=TRUE) 的末尾。如果没有更完整的可重复示例,请配合您的问题,很难说更多。你可以看看this how-to-post
猜你喜欢
  • 1970-01-01
  • 2020-01-07
  • 2013-06-21
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 2014-01-17
相关资源
最近更新 更多