首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >填写缺少的日期并添加“0”

填写缺少的日期并添加“0”
EN

Stack Overflow用户
提问于 2019-03-29 06:09:20
回答 1查看 112关注 0票数 0

下面的代码按滑雪季(12月至3月)每年的月份生成SLC中的雪崩数量。由于此代码获取每年-月份的总数,因此它不会将雪崩次数为0的年份-月份计算在内。我如何填写我的表格,这样它将提供全年-月份?

代码语言:javascript
运行
复制
# write the webscraper
library(XML)
library(RCurl)
library(dplyr)
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 get the  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))
代码语言:javascript
运行
复制
# the data right now looks like this
Date   AvalancheTotal
1980-01        1
1981-02        1
.
.
.



# the data needs to look like this
Date   AvalancheTotal
1980-01        1
1980-02        0
1980-03        0
1980-12        0
1981-01        0
1981-02        1
1981-03        1
EN

回答 1

Stack Overflow用户

发布于 2019-03-29 07:05:00

代码语言:javascript
运行
复制
library("tidyverse")
library("lubridate")

# You data here...

# Simpler version
avalancheslc %>%
  separate(Date, c("year", "month")) %>%
  # Some years might be missing (no avalanches at all)
  # We can fill in those with `full_seq` but
  # `full_seq` works with numbers not characters
  mutate(year = as.integer(year)) %>%
  complete(year = full_seq(year, 1), month,
           fill = list(AvalancheTotal = 0)) %>%
  unite("Date", year, month, sep = "-")

# Alternative version (fills in all months, so needs filtering afterwards)

avalancheslc <- avalancheslc %>%
  # In case `Date` needs parsing
  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 %>%
  right_join(all_months) %>%
  replace_na(list(AvalancheTotal = 0))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55407612

复制
相关文章

相似问题

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