我有一个数据框(测量降水量),其中的日期是沿着柱头。
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
那么,我怎样才能做到这一点? 非常感谢您的帮助。 此致
答案 0 :(得分:0)
这是一个解决方案。你想做两件事
mutate(str_replace)
)arrange
)这是通过以下方式实现的:
library(tidyverse)
tbl <- tibble(
year = rep(1901, 6),
month = 1:6,
X1 = c(9.1, 0, 0, 0, 0, 0),
X2 = rep(0, 6),
X3 = rep(0, 6),
X4 = rep(0, 6),
X5 = c(0, 0.5, 0, 0, 1.8, 0),
X6 = c(0, 0, 0, 0, 4.3, 0)
)
tbl %>%
gather(key = "day", value = "precip", X1:X6) %>%
mutate(day = as.numeric(str_replace(day, "X", ""))) %>%
arrange(year, month, day)
# A tibble: 36 x 4
year month day precip
<dbl> <int> <dbl> <dbl>
1 1901 1 1.00 9.10
2 1901 1 2.00 0
3 1901 1 3.00 0
4 1901 1 4.00 0
5 1901 1 5.00 0
6 1901 1 6.00 0
7 1901 2 1.00 0
8 1901 2 2.00 0
9 1901 2 3.00 0
10 1901 2 4.00 0
# ... with 26 more rows