首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用for循环动态生成数据帧的子集列名

使用for循环动态生成数据帧的子集列名
EN

Stack Overflow用户
提问于 2022-01-19 07:48:32
回答 1查看 126关注 0票数 0

有关以下数据格式的df

代码语言:javascript
运行
复制
df <- structure(list(id = c("M0000607", "M0000609", "M0000612"), `2021-08(actual)` = c(12.6, 
19.2, 8.3), `2021-09(actual)` = c(10.3, 17.3, 6.4), `2021-10(actual)` = c(8.9, 
15.7, 5.3), `2021-11(actual)` = c(7.3, 14.8, 3.1), `2021-12(actual)` = c(6.1, 
14.2, 3.5), `2021-08(pred)` = c(11.65443222, 14.31674997, 7.084180415
), `2021-09(pred)` = c(12.29810914, 17.7143733, 6.057927385), 
    `2021-10(pred)` = c(9.619846116, 15.54553601, 6.525992602
    ), `2021-11(pred)` = c(8.352097939, 13.97318204, 3.164682627
    ), `2021-12(pred)` = c(6.113631596, 14.16243166, 3.288372517
    ), `2021-08(error)` = c(2.082307066, 1.146759554, 0.687406723
    ), `2021-09(error)` = c(1.631350383, 2.753457736, 2.952737781
    ), `2021-10(error)` = c(0.945567783, 4.883250027, 1.215819585
    ), `2021-11(error)` = c(1.998109138, 0.414373304, 0.342072615
    ), `2021-12(error)` = c(0.719846116, 0.154463985, 1.225992602
    )), class = "data.frame", row.names = c(NA, -3L))

假设我的最终目标是重复地将绘图函数应用于df的子集

代码语言:javascript
运行
复制
plot_fun <- function(...)
  ggplot()

更具体地说,我将循环year_months <- c('2021-12', '2021-11', '2021-10')的每个元素并应用plot_fun,因此首先,我需要为year_months的每个元素子集选定的列。

逻辑是:对于特定的年份月份,我将选择: id,最后三个月的实际值,最后一个月的误差和预测值。例如,对于year_month '2021-12', '2021-11', '2021-10',子集列是:

代码语言:javascript
运行
复制
2021-12: selected_cols <- c('id', "2021-10(actual)", "2021-11(actual)", "2021-12(actual)",
                            "2021-12(pred)", "2021-12(error)")

2021-11: selected_cols <- c('id', "2021-09(actual)", "2021-10(actual)", "2021-11(actual)",
                            "2021-11(pred)", "2021-11(error)")

2021-10: selected_cols <- c('id', "2021-08(actual)", "2021-09(actual)", "2021-10(actual)",
                            "2021-12(pred)", "2021-12(error)")

最后,我将像这样运行代码(伪):

代码语言:javascript
运行
复制
for year_month in year_months{
  selected_cols <- ...
  plot_fun(selected_cols)
}

现在,我的问题是如何编写一个for循环函数来为每个选定的year_months生成列名向量?

我为2021-12生成列的试用代码(还不简洁)

代码语言:javascript
运行
复制
date_pre_n_months <- function(end_date, x) {
  floor_date(as.Date(end_date) - months(x), 'month')  
}

end_date <- '2021-12-31'
begin_date <- date_pre_n_months(end_date, 3)

year_month <- seq(as.Date("2021-10-31"), as.Date("2021-12-31"), by = "month")
act <- paste0(strftime(year_month, format="%Y-%m"), '(actual)')
pred <- paste0(strftime(end_date, format="%Y-%m"), '(pred)')
error <- paste0(strftime(end_date, format="%Y-%m"), '(error)')

selected_cols <- c('id', act, pred, error)
selected_cols

退出:

代码语言:javascript
运行
复制
"id"              "2021-10(actual)" "2021-12(actual)" "2021-12(actual)" "2021-12(pred)"   "2021-12(error)"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-19 08:43:42

您可以在基R中这样做,只需lubridate包提供一些帮助。

代码语言:javascript
运行
复制
year_months <- c('2021-12', '2021-11', '2021-10')  
curr <- lubridate::ym(year_months)
prev <- curr - months(2L)
mapply(function(x, y) {
  df[c(
    "id", 
    format(seq.Date(y, x, by = "month"), "%Y-%m(actual)"), 
    format(x, "%Y-%m(pred)"), 
    format(x, "%Y-%m(error)")
  )]
}, curr, prev, SIMPLIFY = FALSE)

输出

代码语言:javascript
运行
复制
[[1]]
        id 2021-10(actual) 2021-11(actual) 2021-12(actual) 2021-12(pred) 2021-12(error)
1 M0000607             8.9             7.3             6.1      6.113632      0.7198461
2 M0000609            15.7            14.8            14.2     14.162432      0.1544640
3 M0000612             5.3             3.1             3.5      3.288373      1.2259926

[[2]]
        id 2021-09(actual) 2021-10(actual) 2021-11(actual) 2021-11(pred) 2021-11(error)
1 M0000607            10.3             8.9             7.3      8.352098      1.9981091
2 M0000609            17.3            15.7            14.8     13.973182      0.4143733
3 M0000612             6.4             5.3             3.1      3.164683      0.3420726

[[3]]
        id 2021-08(actual) 2021-09(actual) 2021-10(actual) 2021-10(pred) 2021-10(error)
1 M0000607            12.6            10.3             8.9      9.619846      0.9455678
2 M0000609            19.2            17.3            15.7     15.545536      4.8832500
3 M0000612             8.3             6.4             5.3      6.525993      1.2158196

如果要将绘图函数应用于选定的数据文件,则

代码语言:javascript
运行
复制
year_months <- c('2021-12', '2021-11', '2021-10')  
curr <- lubridate::ym(year_months)
prev <- curr - months(2L)
plots <- mapply(function(x, y) {
  plot_fun(df[c(
    "id", 
    format(seq.Date(y, x, by = "month"), "%Y-%m(actual)"), 
    format(x, "%Y-%m(pred)"), 
    format(x, "%Y-%m(error)")
  )])
}, curr, prev, SIMPLIFY = FALSE)

给你列了一份阴谋清单。

更新(也可选择当前月份的最后一年)。但是,您需要确保要选择的列存在于dataframe中;否则,您将得到一个错误。

代码语言:javascript
运行
复制
year_months <- c('2021-12', '2021-11', '2021-10')  
curr <- lubridate::ym(year_months)
prev <- curr - months(2L)
mapply(function(x, y) {
  df[c(
    "id", 
    format(c(x - lubridate::years(1L), seq.Date(y, x, by = "month")), "%Y-%m(actual)"),  
    format(x, "%Y-%m(pred)"), 
    format(x, "%Y-%m(error)")
  )]
}, curr, prev, SIMPLIFY = FALSE)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70766957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档