見出し画像

tidyr::gather を使用した変換

概要


積み上げグラフを書くためにgather を使用してデータを変換する。gather はワイド型のデータをロング型に変換してくれる。以下の例では第二列から第九列までを一列にまとめる。指定に際しては列名を使用する。引数、c("10", "20", "30", "40", "50", "60", "70", "80")がそれに相当する。ロング型とワイド型については以下を参照のこと。

tidyr::gather()を使用したサンプルコード 

​
df <- data.frame(t=xts::last(index(v),length_graph),
# o=xts::last(diff(all[,1]-all[,3],t=all[,3]),length_graph),
a=xts::last(v[,1],length_graph),
b=xts::last(v[,2],length_graph),
c=xts::last(v[,3],length_graph),
d=xts::last(v[,4],length_graph),
e=xts::last(v[,5],length_graph),
f=xts::last(v[,6],length_graph),
g=xts::last(v[,7],length_graph),
h=xts::last(v[,8],length_graph)
# or=xts::last(all[,2],length_graph)*multi,
# kr=xts::last(all[,2],length_graph)*multi
)
for(i in seq(1,8,1)){
colnames(df)[i+1] <- as.character(i*10)
}
df.melt <- df  %>% tidyr::gather(variable,value,c("10", "20", "30", "40", "50", "60", "70", "80"))
#
#
#
df <- df.melt
# in order to overlayer graph use ggplot(NULL) to create base object.
g <- ggplot(NULL)
# g <- ggplot(df, aes(x = t, y = value, fill = variable))
g <- g + scale_fill_brewer(palette="Spectral",na.value = "black",name = "age group", direction=-1,labels = c("=<19",">=20",">=30",">=40",">=50",">=60",">=70",">=80"))
g <- g + geom_bar(data=df,aes(x = t, y = value, fill = variable),stat = "identity")
plot(g)

上記の例は単純にt列だけを除いて変換しても良い。その場合は

df.melt <- df  %>% tidyr::gather(variable,value,-t)

となる。結果は同様になるはずである。

変換前データ


> head(df)
                   t   10   20   30   40  50  60  70  80
2022-04-20 2022-04-20 2202 1114 1194 1000 547 234 165 122
2022-04-21 2022-04-21 2126 1223 1247 1066 527 205 179 136
2022-04-22 2022-04-22 1640  996  995  847 459 205 135 115
2022-04-23 2022-04-23 1661  982  965  854 486 208 119 111
2022-04-24 2022-04-24 1664  827  863  822 386 163 112  98
2022-04-25 2022-04-25 1044  545  564  454 265 131  77  56


変換後データ


> head(df.melt[df.melt$variable=='10',])
          t variable value
1 2022-04-20       10  2202
2 2022-04-21       10  2126
3 2022-04-22       10  1640
4 2022-04-23       10  1661
5 2022-04-24       10  1664
6 2022-04-25       10  1044
> head(df.melt[df.melt$variable=='20',])
           t variable value
80 2022-04-20       20  1114
81 2022-04-21       20  1223
82 2022-04-22       20   996
83 2022-04-23       20   982
84 2022-04-24       20   827
85 2022-04-25       20   545
> head(df.melt[df.melt$variable=='80',])
            t variable value
554 2022-04-20       80   122
555 2022-04-21       80   136
556 2022-04-22       80   115
557 2022-04-23       80   111
558 2022-04-24       80    98
559 2022-04-25       80    56

この記事が気に入ったらサポートをしてみませんか?