简体   繁体   中英

Reshape data using pivot_wider function

I have the following data frame and am trying to reshape it from long to wide using the pivot_wider function but can't seem to figure out the error.

'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.

Thanks for the help.

For names_from and friends, reference the name of the column, not the column itself.

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    

This also works with non-standard evaluation (NSE):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM