使用ivot_wider函数重塑数据

问题描述

我有以下数据框,并尝试使用ivot_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.

感谢您的帮助。

解决方法

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

z <- data.frame(ID = c(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)