将长格式数据帧转换为宽格式 tidyverse [英] converting a long-formated dataframe to wide format tidyverse
本文介绍了将长格式数据帧转换为宽格式 tidyverse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面我首先成功地对我的 dat
进行了长格式,但是当我尝试将其转换回原始的宽格式时,我没有得到相同的输出.
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
推荐答案
试试这个.函数的某些元素没有被正确理解.将变量放在正确的参数中可以获得所需的输出.代码如下:
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)
输出:
# 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
这篇关于将长格式数据帧转换为宽格式 tidyverse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文