【问题标题】:select the data by month and years in R在R中按月和年选择数据
【发布时间】:2021-07-30 10:16:06
【问题描述】:

我有一个按月和年排序的数据框。我只想选择整数年,即如果数据从 2002 年 7 月开始,到 2010 年 9 月结束,那么只选择 2002 年 7 月到 2010 年 6 月的数据。 如果数据从 1992 年 9 月开始,到 2000 年 3 月结束,则只选择 1992 年 9 月到 1999 年 8 月之间的数据。不管这期间缺少多少个月。

可以从以下链接上传数据: enter link description here

代码

mydata <- read.csv("E:/mydata.csv", stringsAsFactors=TRUE)

这是手动选择

selected.data <- mydata[1:73,]   # July 2002 to June 2010 

如何通过编码来实现。

【问题讨论】:

  • @Ronak Shah 通常从一月开始,到十二月 (12) 个月结束。但如果数据从 7 月开始,那么我想选择 6 月结束。 2002 年 7 月到 2003 年 6 月,这是一个整数年,第二个整数年是 2003 年 7 月到 2004 年 6 月,依此类推,直到最后一行。在 mydata 中,我们看到数据在 2010 年 9 月结束,并且应该在 2010 年 6 月结束。通过在开始月份添加 12 来找到我想要保留的月份。如果是 7 月,则选择到 6 月。如果是 May 选择到 April 等等

标签: r select


【解决方案1】:

这是一个基本的 R 单线:

result <- mydata[seq_len(with(mydata, which(Month == month.name[match(Month[1],
                         month.name) - 1] & Year == max(Year)))), ]

head(result)

#     Month Year       var
#1     July 2002 -91.22997
#2  October 2002 -91.19007
#3 December 2002 -91.05395
#4 February 2003 -91.16958
#5    March 2003 -91.17881
#6    April 2003 -91.15110

tail(result)
#      Month Year       var
#68 December 2009 -90.92610
#69  January 2010 -91.07379
#70 February 2010 -91.12460
#71    March 2010 -91.10288
#72    April 2010 -91.06040
#73     June 2010 -90.94212 

【讨论】:

  • 您的代码在除 1 月以外的开始月份的情况下运行良好,但如果 1 月是列(月份)中的第一个月,那么当从中减去 1 时将得到 0。知道如何处理这个问题?
【解决方案2】:

这是一个基本解决方案,可重现您的手动子集:

mydata <- read.csv("D:/mydata.csv", stringsAsFactors=F)
lookup <-
  c(
    January = 1,
    February = 2,
    March = 4,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12
  )
mydata$Month <- unlist(lapply(mydata$Month, function(x) lookup[match(x, names(lookup))]))

first.month <- mydata$Month[1]
last.year <- max(mydata$Year)
mydata[1:which(mydata$Month==(first.month -1)&mydata$Year==last.year),]

基本上,我将月份名称转换为数字,并找到数据框中出现的第一个月之前的月份,即数据框的最后一年。

【讨论】:

  • @Elia 还有一个问题,如果去年不包含例如六月(缺少)在这种情况下,我需要将 if 语句返回到去年的前一年。那怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 2018-12-24
  • 1970-01-01
相关资源
最近更新 更多