下面,我首先成功地对dat
进行了长格式设置,但是当我尝试将其转换回其原始的宽格式时,却没有得到相同的输出。
是否有此解决方法?
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
答案 0 :(得分:2)
尝试一下。该功能的某些元素未正确理解。将变量放在正确的参数中可以获取所需的输出。这里的代码:
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
答案 1 :(得分:0)
您使用的是参数默认顺序,第一个参数(data =
之后)是id_cols,在您旋转后可以将其保留为列。第二个参数是names_from,您将其设置为grad_rate
dat %>%
pivot_wider(values_from = grad_rate,
names_from = year,
id_cols = State:Abbr)