提问人:NeverLate 提问时间:8/18/2023 最后编辑:DaveArmstrongNeverLate 更新时间:8/20/2023 访问量:40
使用 for 循环将过滤器和 rbind 组合到新的数据框
Using for loop to combine a filter and rbind to a new data frame
问:
我有如图所示的数据,我想按年份列过滤数据,同时确保月份是连续的,如下图所示
我使用以下方法完成了上述操作
gs2_1959 <- filter(g2, Year == "1959/60")
gs2_1960 <- filter(g2, Year == "1960/61")
temp <- rbind(gs2_1959, gs2_1960)
但是,如果有很多年,这将是一个痛苦的过程,因为我必须每年进行过滤。
我一直在尝试像这样使用for循环
for (i in seq_along(gs2_unique)){
gs_filter <- filter(g2, i %in% gs2_unique)
View(gs_filter)
} # where unique is the unique years in my data frame.
这将以原始格式保留年份(请参阅原始数据图像)。原始图像
答:
0赞
Mark
8/20/2023
#1
我是这样做的:不要将日期放在三个不同的列中,而是将“年”、“日”和“月”列合并为一列:
df |>
mutate(Date = as.Date(paste0(str_extract(Year, "^\\d{4}"), months, Day), "%Y%b%d"),
Date = if_else(month(Date) < 7, Date + years(1), Date), .before = 1, .keep = "unused") |> # I assume because it looks like football season data, the early year dates are going to be for the first half of the second year, not the first year, so we add one
arrange(Date)
输出:
Date flow
1 1959-10-23 9.328
2 1959-10-24 7.868
3 1959-10-25 7.424
4 1959-10-26 7.024
5 1959-10-27 6.263
6 1959-10-28 5.739
7 1959-10-29 5.241
8 1959-10-30 5.090
9 1959-10-31 4.646
10 1960-10-01 6.263
11 1960-10-02 5.526
12 1960-10-03 5.090
13 1960-10-04 4.623
14 1960-10-05 4.882
15 1960-10-06 5.500
上一个:R 中缺少数据文件
评论
g2 %>% arrange(year, month, day)