为什么不能得到一个矢量类

时间:2018-03-05 08:57:48

标签: r

我已经提取了这个数据框:

> df<-as.data.frame(model_rf$variable.importance)
> df
                            Importance
DayOfWeek                 3.763932e+11
Customers                 1.364059e+12
Open                      6.345289e+11
Promo                     2.617495e+11
StateHoliday              5.196666e+09
SchoolHoliday             6.522969e+09
DateYear                  7.035399e+09
DateMonth                 2.013482e+10
DateDay                   3.763177e+10
DateWeek                  3.283496e+10
StoreType                 3.156843e+10
Assortment                2.025741e+10
CompetitionDistance       1.118476e+11
CompetitionOpenSinceMonth 4.633220e+10
CompetitionOpenSinceYear  4.554890e+10
Promo2                    0.000000e+00
Promo2SinceWeek           5.066674e+10
Promo2SinceYear           4.096407e+10
CompetitionOpen           3.992745e+10
PromoOpen                 2.831936e+10
IspromoinSales            2.844220e+09

然后我想在其他列中提取值:

> v<-as.vector(model_rf$variable.importance$Importance)
> v
 [1] 3.763932e+11 1.364059e+12 6.345289e+11 2.617495e+11 5.196666e+09 6.522969e+09 7.035399e+09 2.013482e+10 3.763177e+10
[10] 3.283496e+10 3.156843e+10 2.025741e+10 1.118476e+11 4.633220e+10 4.554890e+10 0.000000e+00 5.066674e+10 4.096407e+10
[19] 3.992745e+10 2.831936e+10 2.844220e+09

其他列中每行的名称

> w<-(as.vector((row.names(df))))
> w
 [1] "DayOfWeek"                 "Customers"                 "Open"                      "Promo"                    
 [5] "StateHoliday"              "SchoolHoliday"             "DateYear"                  "DateMonth"                
 [9] "DateDay"                   "DateWeek"                  "StoreType"                 "Assortment"               
[13] "CompetitionDistance"       "CompetitionOpenSinceMonth" "CompetitionOpenSinceYear"  "Promo2"                   
[17] "Promo2SinceWeek"           "Promo2SinceYear"           "CompetitionOpen"           "PromoOpen"                
[21] "IspromoinSales" 

然后我需要获得由上面的两个向量创建的数据框:

DF<-as.data.frame(w,v)
  
    

DF&lt; -as.data.frame(w,v)警告信息:在as.data.frame.vector(x,...,nm = nm)中:&#39; row.names&#39;不是长度为21的字符向量      - 省略它。将是一个错误!

  

事实上,即使我做as.vector,w矢量似乎也不会被转换为矢量类。它仍然是character类。

> class(w)
[1] "character"

你怎么解释这个?

2 个答案:

答案 0 :(得分:1)

试试这段代码:

DF<-as.data.frame(cbind(w,v))

答案 1 :(得分:1)

如果查看as.data.frame的文档,您会发现函数需要第二个向量作为行名称的字符向量。

在您的情况下,您首先提供行名称,然后提供值,从而导致上述错误。

您可以使用

as.data.frame(v,w)

data.frame(w,v)

获得理想的结果。