library(tidyverse)
<-data.frame(region=LETTERS[1:3],
data_longeryear=rep(2019:2023,each=3),
case=round(runif(15)*100))
data_longer
17 长宽数据转换
17.0.1 长转宽
<-data_longer %>%
data_wider1pivot_wider(id_cols = year,names_from = 'region',values_from = 'case' )
data_wider1
<-data_longer %>%
data_wider2pivot_wider(id_cols = region,names_from = 'year',names_prefix = 'y_',values_from = 'case' )
data_wider2
17.0.2 宽转长
<-data_wider1 %>%
data_longer2pivot_longer(c(A,B,C),names_to = 'region',values_to='count')
data_longer2
17.0.3 作图多用长数据
ggplot(data_longer,aes(factor(year),y=case,fill=region))+
geom_col(position = 'dodge')+
theme_bw()+
::scale_fill_jama() ggsci