【发布时间】:2018-07-19 08:32:00
【问题描述】:
我有一个数据框(测量降水量),其中日期沿列标题。
Observations: 1,195
Variables: 33
$ Year <int> 1901, 1901, 1901, 1901, 1901, 1901, 1901, 1901, 1901, 190...
$ Month <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, ...
$ X1 <dbl> 9.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.6, 0.0, 0.0, 0.0, 0....
$ X2 <dbl> 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 12.4, 0.0, 0.0, 0.0, 0...
$ X3 <dbl> 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0....
$ X4 <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
$ X5 <dbl> 0.0, 0.5, 0.0, 0.0, 1.8, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0....
$ X6 <dbl> 0.0, 0.0, 0.0, 0.0, 4.3, 0.0, 0.0, 11.7, 0.0, 0.0, 0.0, 0...
我想将其转换为长格式,其中按天数也在一列中。 我用过:
library(tidyr)
long <- gather(dataframe, Day, PCP, -Month,-Year)
输出是:
head(long)
Year Month Day PCP
1 1901 1 X1 9.1
2 1901 2 X1 0.0
3 1901 3 X1 0.0
4 1901 4 X1 0.0
5 1901 5 X1 0.0
6 1901 6 X1 0.0
我希望输出如下所示,其中每个月都按顺序与其天数相关联:
Year Month Day PCP
1 1901 01 01 9.1
2 1901 01 02 0.0
3 1901 01 03 0.0
4 1901 01 04 0.0
5 1901 01 05 0.0
6 1901 01 06 0.0
那么,我该如何实现呢? 您的帮助将不胜感激。 问候
【问题讨论】:
-
随意排序,例如
library(dplyr); long %>% arrange(Year, Month, Day)。您可能还想删除Xs,例如mutate(Month = readr::parse_number(Month)) -
以可复制格式提供样本数据通常是值得赞赏的