【问题标题】:Reshape data using pivot_wider function使用 pivot_wider 函数重塑数据
【发布时间】:2020-08-21 16:33:02
【问题描述】:

我有以下数据框,正在尝试使用 pivot_wider 函数将其从长到宽重塑,但似乎无法找出错误。

'data.frame':   376654 obs. of  3 variables:
 $ Investment.ID   : int  4 4 4 4 4 4 4 4 4 5 ...
 $ Attribute.Column: chr  "Active Relationship Type" "Asset Class" "CEM Survey Classification" "Emerging Manager Detail" ...
 $ Attribute.Name  : chr  "Non-Core" "Private Equity" "External (incl. Growth Equity & Energy)" "MWBE" ...

tbl.PivotedInvAttrStacked <- pivot_wider(tbl.InvestAttrStacked,
        names_from = tbl.InvestAttrStacked$Attribute.Column,
        values_from = tbl.InvestAttrStacked$Attribute.Name,
        values_fill = NULL)

Error: Can't subset columns that don't exist.
x Columns `Active Relationship Type`, `Asset Class`, `CEM Survey Classification`, `Emerging Manager Detail`, `Emerging Manager Detail L2`, etc. don't exist.

感谢您的帮助。

【问题讨论】:

  • dput(tbl.InvestAttrStacked) 并粘贴您的问题以帮助您!

标签: r pivot reshape


【解决方案1】:

对于names_from 和朋友,请引用列的名称,而不是列本身。

z <- data.frame(ID = c(4,4,4,4), Attribute.Column=c("Active", "Asset", "CEM", "Emerging"), Attribute.Name=c("Non-Core", "Private Equity", "External (incl. Growth Equity & Energy)", "MWBE"))
z
#   ID Attribute.Column                          Attribute.Name
# 1  4           Active                                Non-Core
# 2  4            Asset                          Private Equity
# 3  4              CEM External (incl. Growth Equity & Energy)
# 4  4         Emerging                                    MWBE

library(dplyr)
library(tidyr)
z %>%
  pivot_wider("ID", names_from="Attribute.Column", values_from="Attribute.Name", values_fill = NULL)
# # A tibble: 1 x 5
#      ID Active   Asset          CEM                                     Emerging
#   <dbl> <chr>    <chr>          <chr>                                   <chr>   
# 1     4 Non-Core Private Equity External (incl. Growth Equity & Energy) MWBE    

这也适用于非标准评估 (NSE):

z %>%
  pivot_wider(ID, names_from=Attribute.Column, values_from=Attribute.Name, values_fill = NULL)

【讨论】:

    猜你喜欢
    • 2022-12-06
    • 2020-07-11
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多