【问题标题】:Subsetting Data based on selected months in R基于 R 中选定月份的子集数据
【发布时间】:2017-02-02 04:01:13
【问题描述】:
Year         tot_precip
1/1/1989     0
1/2/1989    .23
1/3/1989    0
1/4/1989    .43
1/5/1989    0.254
1/6/1989    0
1/7/1989    0
1/8/1989    0
1/9/1989    0
1/10/1989   .21

我正在尝试根据某些月份对我的降水数据进行子集化。我做了一些研究。

tt=as.POSIXct(paste(prec$Year,prec$tot_precip), format="%m/%d/%Y")
datZoo <- zoo(prec[,-c(1,2)], tt)
month <- function (x) as.numeric(format(x, "%m"))
veranoIdx <- which(month(tt) %in% 6:8)
veranoZoo <- datZoo[veranoIdx]
veranoZoo

上面的代码可以根据某些月份(6 月、7 月 8 月)提取年份列,但我不知道如何提取这些日期的降水值(即 veranoZoo 系列)

【问题讨论】:

    标签: r


    【解决方案1】:

    假设Lines 如下注所示,将数据读入动物园对象。由于这显然是月度数据,因此最好使用"yearmon" 类作为索引。现在使用subset 获取六月、七月、八月的子集。

    z <- read.zoo(text = Lines, header = TRUE, FUN = as.yearmon, format = "%d/%m/%Y")
    subset(z, cycle(z) %in% 6:8)
    

    给这个动物园系列:

    Jun 1989 Jul 1989 Aug 1989 
           0        0        0 
    

    这也可以:

    z[cycle(z) %in% 6:8]
    

    (如果您的数据在文件 myfile.dat 中,则在 read.zoo 语句中将 text=Lines 替换为 "myfile.dat"。)

    注意:

    Lines <- "Year tot_precip
    1/1/1989 0
    1/2/1989 .23
    1/3/1989 0
    1/4/1989 .43
    1/5/1989 0.254
    1/6/1989 0
    1/7/1989 0
    1/8/1989 0
    1/9/1989 0
    1/10/1989 .21"
    

    【讨论】:

    • @G. Grothendieck 谢谢。我试过上面的代码。但是我在 FUN=as.yearman 上遇到了一些错误。我更改了没有 FUN=as.yearman 的代码,如下 wood=read.csv(file = "woodruff.csv",header=TRUE) wood[is.na(wood)]
    • 必须使用yearmon才能使用cycle。
    • k
    • 正如警告所说,动物园对象不能有重复的时间。问题中的数据没有。
    【解决方案2】:

    考虑输入为:

    dft <- read.table(header = TRUE, text = "Year         tot_precip
    
                      1/1/1989     0
    
                      1/2/1989    .23
    
                      1/3/1989    0
    
                      1/4/1989    .43
    
                      1/5/1989    0.254
    
                      1/6/1989    0
    
                      1/7/1989    0
    
                      1/8/1989    0
    
                      1/9/1989    0
    
                      1/10/1989   .21",stringsAsFactors=FALSE)
    

    您可以使用tidyverse 函数并尝试:

    dft %>% filter(month(Year) %in% c(6,7,8))
    

    给出:

          Year tot_precip
    1 1/6/1989          0
    2 1/7/1989          0
    3 1/8/1989          0
    

    【讨论】:

    • 我尝试了以下代码。 wood=read.csv(file = "woodruff.csv",header=TRUE) wood[is.na(wood)]% filter(month( Year) %in% c(6,7,8)) 我现在得到的错误是 Filter_impl(.data, dots) 中的错误:字符串不是标准的明确格式
    • 很可能您的Year 格式不正确。您可以查看日期时间类型 n R 及其conversion functions
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2023-04-08
    相关资源
    最近更新 更多