【问题标题】:Build a table by pasting rows extracted from subsets based on a value通过粘贴从基于值的子集中提取的行来构建表
【发布时间】:2019-08-22 16:42:41
【问题描述】:

我有 1970 年到 2019 年的每日库存数据子集。我的目标是在一列中获取每年发生最小值的日期,在另一列中获取最小值。我可以遍历子集以使用“foreach”、“.combine=rbind”、“lapply”和“which.min”来构建我想要但我无法获得的行列表以这种方式超出索引的日期。

    mindates <- foreach(i = 1:length(GSPC_yearly), .combine=rbind) %do% {
    # I would like to be able to attach the corresponding row label date from the index to this code
          spyannmin<-as.numeric(lapply(GSPC_yearly[[i]]$GSPC.Low,min))
          spyannmindate<-(lapply(GSPC_yearly[[i]]$GSPC.Low,which.min))

     # Or be able to bind this code row wise because its output already includes the row label date from the index of the source data.  This is only giving me the result of the last [[i]], i want a table of rows with all the [[i]]'s       
           spyannmindexdate<-GSPC_yearly[[i]][spyannmindate,3]

      result.data<-c(spyannmin, spyannmindate,spyannmindexdate)
           }

head(mindates,3)
spyannmindexdate

这给了我这样的输出...

                    GSPC.Low       
result.1 68.61  101      68.61 
result.2 89.34  227      89.34 
result.3 100.87 2        100.87
# But I would like the date to appear where the result.# appears or in a new column, I'm not sure which would be better.

           GSPC.Low
2019-01-03  2443.96
# Or I would like this data exactly, but pasted with the respective row from each yearly subset of the larger source data.  Again I want output that  includes the row for each year.

如果我只使用“which.min”来获取行索引,那么我可以获得日期和最小值但没有“lapply”我不知道如何使用“.combine=rbind”构建表

所以我有两种方法可以解决我的问题,但每种方法都缺少一个关键要素。我将不胜感激任何一个解决方案。两者的解决方案将有助于提高我对 r 编程的理解。提前谢谢你。

【问题讨论】:

    标签: r foreach rbind


    【解决方案1】:

    这是一种快速而肮脏的方法:

    library(dplyr)
    
    df <- 
      tribble(
        ~year, ~date, ~price,
        2018, "2018-12-30", 30,
        2018, "2018-12-31", 32,
        2019, "2019-01-01", 34,
        2019, "2019-01-02", 36,
        2019, "2019-01-03", 35
      )
    
    df %>% 
      group_by(year) %>% 
      filter(price == min(price)) %>% 
      ungroup()
    
    # A tibble: 2 x 3
       year date       price
      <dbl> <chr>      <dbl>
    1  2018 2018-12-30    30
    2  2019 2019-01-01    34
    

    【讨论】:

    • 感谢红衣主教。我仍然需要一些方法来从索引中获取日期。然后我可以创建列~year。我猜它正在访问我真正遇到问题的原始数据 xts 对象的索引。另外,有没有办法将我的数据读入 tribble 或者需要手动输入?我读入的 xts 对象有 12522 行和 6 列加上包含日期的索引。我试图将其转换为 data.frame 以查看是否可以更轻松地使用它,但到目前为止还没有。我正在尽可能多地阅读以尝试在文档中找到解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    相关资源
    最近更新 更多