【问题标题】:How to remove multiple year-months from a dataset如何从数据集中删除多个年月
【发布时间】:2019-08-19 20:56:52
【问题描述】:

我有这个数据集,但只需要 1、2、3、12 个月,并且只需要与这些月份相关的所有年份。日期的格式是年月,我需要保持这种方式最终与另一个数据集合并。谢谢你的帮助

# write the webscraper
library(XML)
library(RCurl)
library(dplyr)
library('zoo')
library('tidyverse')
library('lubridate')
avalanche<-data.frame()
avalanche.url<-"https://utahavalanchecenter.org/observations?page="
all.pages<-0:202
for(page in all.pages){
  this.url<-paste(avalanche.url, page, sep="")
  this.webpage<-htmlParse(getURL(this.url))
  thispage.avalanche<-readHTMLTable(this.webpage, which=1, header=T,stringsAsFactors=F)
  names(thispage.avalanche)<-c('Date','Region','Location','Observer')
  avalanche<-rbind(avalanche,thispage.avalanche)
}

# subset the data to the Salt Lake Region
avalancheslc<-subset(avalanche, Region=="Salt Lake")
str(avalancheslc)

# convert the dates and total the number of avalanches
avalancheslc <- avalancheslc %>% 
          group_by(Date = format(as.yearmon(Date, "%m/%d/%Y"), "%Y-%m")) %>% 
          summarise(AvalancheTotal = n())
# pipe to only include Dec-Mar of each year
avalancheslc <- avalancheslc %>% filter(as.integer(substr(Date, 6, 7)) %in% c(12, 1:3))




avalancheslc <- avalancheslc %>% mutate(Date = parse_date_time(Date, "%y-%m"))


# A full data frame of months
all_months <- avalancheslc %>% expand(Date = seq(first(Date), last(Date), by = "month"))

# Join to `avalanches` and fill in with 0s
avalancheslc <- avalancheslc %>% right_join(all_months) %>% replace_na(list(AvalancheTotal = 0))

# convert date back to Year-Month format
avalancheslc$Date<-format(avalancheslc$Date, "%Y-%m")


应该是这样的

Date    AvalancheTotal
1980-01         1
1980-02         0
1980-03         0
1980-12         0
1981-01         0
1981-02         1
..
.
.
.
2019-03        163

【问题讨论】:

  • 您在哪一步需要帮助?
  • 现在我的代码会得到所有年份和所有月份,而我想要所有年份,但只需要 1 月、2 月、3 月和 12 月的几个月。

标签: r


【解决方案1】:

您可以使用lubridate 包来实现类似的功能。 使用month,它提取月份的整数值,并根据您的要求进行过滤,因此,

library(dplyr)
library(lubridate)
df %>%
  filter(month(date) %in% c(1, 2, 3, 12))

【讨论】:

  • ...r 返回错误:“错误:评估错误:不知道如何将 'x' 转换为类 POSIXlt”
  • 我将日期固定为 Date 但错误仍然存​​在:“错误:评估错误:字符串不是标准的明确格式。”
  • 没关系...只需切换最后两行就可以了
猜你喜欢
  • 2019-09-21
  • 2019-04-21
  • 2020-11-21
  • 1970-01-01
  • 2023-02-19
  • 2020-01-07
  • 1970-01-01
  • 2015-08-23
  • 2018-11-12
相关资源
最近更新 更多