【问题标题】:Turning a dataframe into a named vector将数据框转换为命名向量
【发布时间】:2020-02-02 17:45:28
【问题描述】:

我在我的 dfm 上应用了一个模型(wordscore)。结果,我得到了一个输出对象,其类是“textmodel_wordscores”“textmodel”“list”。我对输出“wordscores”感兴趣,它是一个“数字”对象(这是当 class 应用于对象时所说的),如下所示:

           extensive      fiscal_stimulus              measure           operation  automatic_stabiliser 
          0.96765485           0.98292581          -0.70247675           0.63275195           0.75272326 
                will 
         -0.04568423

现在我有一个包含两列的普通数据框,如下所示:

df <- data.frame(Words = c("commitment", "progress", "implement", "decision", "message", "deficit"), Score = c(-0.984345245754151, -0.983153011766781, -0.978586816039627, -0.977724303324149, -0.976291875611652, -0.975229993562152))

    Words              Score
1 commitment -0.984345245754151
2   progress -0.983153011766781
3  implement -0.978586816039627
4   decision -0.977724303324149
5    message -0.976291875611652
6    deficit -0.975229993562152

我希望此数据框与上述格式相同。我试图转换为列表,但它保留了双列框架。

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:

    你可以这样做:

    with(df, setNames(Score, Words))
    
    commitment   progress  implement   decision    message    deficit 
    -0.9843452 -0.9831530 -0.9785868 -0.9777243 -0.9762919 -0.9752300 
    

    【讨论】:

    • 很好的答案,效果很好,非常感谢!我将标记为正确的堆栈允许我这样做(技术时间)
    【解决方案2】:

    我们也可以使用deframe

    library(tibble)
    deframe(df)
    #commitment   progress  implement   decision    message    deficit 
    #-0.9843452 -0.9831530 -0.9785868 -0.9777243 -0.9762919 -0.9752300 
    

    在base R中,names&lt;-也可以使用

    with(df, `names<-`(Score, Words))
    

    【讨论】:

      猜你喜欢
      • 2013-10-16
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2017-09-25
      • 2022-07-06
      • 2020-01-01
      相关资源
      最近更新 更多