首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从数据集中删除多个年份-月份

如何从数据集中删除多个年份-月份
EN

Stack Overflow用户
提问于 2019-03-29 07:57:09
回答 1查看 37关注 0票数 0

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

代码语言:javascript
复制
# 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")

应该看起来像这样

代码语言:javascript
复制
Date    AvalancheTotal
1980-01         1
1980-02         0
1980-03         0
1980-12         0
1981-01         0
1981-02         1
..
.
.
.
2019-03        163
EN

回答 1

Stack Overflow用户

发布于 2019-03-29 16:46:26

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

代码语言:javascript
复制
library(dplyr)
library(lubridate)
df %>%
  filter(month(date) %in% c(1, 2, 3, 12))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55408589

复制
相关文章

相似问题

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