converting a long-formated dataframe to wide format tidyverse [duplicate]

我与影子孤独终老i 提交于 2021-02-04 16:45:31

问题


Below I first successfully long-format my dat, but when I try to convert it back to its original wide-format I don't get the same output.

Is there a fix for this?

library(tidyverse)

ACGR <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/ACGR%202010-11%20to%202016-17.csv', na = "---")

dat <- ACGR %>% 
  pivot_longer(names_to = "year", values_to = "grad_rate", cols = SY2010_11:SY2016_17)


dat %>%
pivot_wider(year, grad_rate)  ## doesn't return to ACGR format HERE

  year     
  <chr>    
1 SY2010_11
2 SY2011_12
3 SY2012_13
4 SY2013_14
5 SY2014_15
6 SY2015_16
7 SY2016_17

回答1:


Try this. Some elements of the function are not being understood properly. Placing the variables in the right argument allows obtaining the desired output. Here the code:

library(tidyverse)
#Code
Widedata <- dat %>%
  pivot_wider(names_from=year, values_from=grad_rate)

Output:

# A tibble: 51 x 9
   State                Abbr  SY2010_11 SY2011_12 SY2012_13 SY2013_14 SY2014_15 SY2015_16 SY2016_17
   <fct>                <fct>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>
 1 Alabama              AL           72        75      80        86.3      89.3      87.1      89.3
 2 Alaska               AK           68        70      71.8      71.1      75.6      76.1      78.2
 3 Arizona              AZ           78        76      75.1      75.7      77.4      79.5      78  
 4 Arkansas             AR           81        84      84.9      86.9      84.9      87        88  
 5 California           CA           76        79      80.4      81        82        83        82.7
 6 Colorado             CO           74        75      76.9      77.3      77.3      78.9      79.1
 7 Connecticut          CT           83        85      85.5      87        87.2      87.4      87.9
 8 Delaware             DE           78        80      80.4      87        85.6      85.5      86.9
 9 District of Columbia DC           59        59      62.3      61.4      68.5      69.2      73.2
10 Florida              FL           71        75      75.6      76.1      77.9      80.7      82.3
# ... with 41 more rows



回答2:


You are relying on the argument default orders, the first (after data = ) argument is id_cols which can be kept as a column after you pivot. The second argument is names_from which you set as grad_rate

dat %>%
  pivot_wider(values_from = grad_rate,
              names_from = year, 
              id_cols = State:Abbr)


来源:https://stackoverflow.com/questions/64542210/converting-a-long-formated-dataframe-to-wide-format-tidyverse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!