在R中,将“ 10月29日至11月1日”转换为“ 20201029”和“ 20201101”

如何解决在R中,将“ 10月29日至11月1日”转换为“ 20201029”和“ 20201101”

我正在处理从网站刮掉的凌乱表格,为了使日期列更有用,我需要清理刮掉的东西。我们的数据如下所示:

mydata <- structure(list(Dates = c("Sep\r\n            \r\n            10 - 13","Oct\r\n            \r\n            8 - 11","Oct 29 - Nov 1","Nov\r\n            \r\n            19 - 22","Jan\r\n            \r\n            21 - 24","Mar\r\n            \r\n            4 - 7","Apr 29 - May 2"),points = c("500","500","550","500"
    )),row.names = c(1L,5L,8L,11L,16L,23L,32L),class = "data.frame")


> mydata
                                        Dates points
1  Sep\r\n            \r\n            10 - 13    500
5   Oct\r\n            \r\n            8 - 11    500
8                              Oct 29 - Nov 1    500
11 Nov\r\n            \r\n            19 - 22    500
16 Jan\r\n            \r\n            21 - 24    500
23   Mar\r\n            \r\n            4 - 7    550
32                             Apr 29 - May 2    500

Dates中的每个日期都是一个日期范围,实际上应该是startDateendDate。然后我们要创建的是:

> newdata
     StartDate   EndDate  points
1     20200910  20200913     500
1     20201008  20201011     500
1     20201029  20201101     500
1     20201119  20201122     500
1     20210121  20210124     500
1     20210304  20210307     500
1     20210429  20210502     500

我们可以假设9月至12月的所有日期都是2020年,而1月至8月的所有日期都是2021年。

编辑1

这也许不是最干净的代码,但是我成功地将Dates列分为两列

  cleaning_dates_df <- do.call('rbind',strsplit(mydata$Dates,'-')) %>% as.data.frame()
  colnames(cleaning_dates_df) <- c('start','end')
  cleaning_dates_df$start <- as.character(cleaning_dates_df$start)
  cleaning_dates_df$end <- as.character(cleaning_dates_df$end)
  cleaning_dates_df <- cleaning_dates_df %>%
    dplyr::mutate(end = ifelse(nchar(end) > 4,end,paste0(trimws(sub("\r\n.*","",start)),end))) %>%
    dplyr::mutate(start = ifelse(nchar(start) < 8,start,sub(".*\\s",start)))) %>%
    dplyr::mutate(end = trimws(end)) %>% dplyr::mutate(start = trimws(start))

  head(cleaning_dates_df,8)

...仍然需要转换为YYYYMMDD

解决方法

我不会称它为漂亮,但是您可以使用regex首先抓取所有部分:

rgx <- "^([a-z]+)(\\r|\\n|\\s)+(\\d+)\\s\\-\\s([a-z]+)*\\s*(\\d+)$"
td <- strcapture(rgx,tolower(mydata$Dates),proto=list(mth1="",x="",day1="",mth2="",day2=""))

仅提及一个月时重复一个月:

td$mth2[td$mth2 == ''] <- td$mth1[td$mth2 == '']

将月份转换为数字,然后确定是2020还是2021:

td[c("mth1","mth2")] <- lapply(td[c("mth1","mth2")],function(x) match(x,tolower(month.abb)))
td[c("yr1","yr2")]   <- lapply(td[c("mth1",function(x) ifelse(x >= 9,2020,2021) )

从各个部分构造日期:

mydata$startdate <- as.Date(paste(td$yr1,td$mth1,td$day1,sep="/"))
mydata$enddate   <- as.Date(paste(td$yr2,td$mth2,td$day2,sep="/"))

完成!:

mydata

#                                        Dates points  startdate    enddate
#1  Sep\r\n            \r\n            10 - 13    500 2020-09-10 2020-09-13
#5   Oct\r\n            \r\n            8 - 11    500 2020-10-08 2020-10-11
#8                              Oct 29 - Nov 1    500 2020-10-29 2020-11-01
#11 Nov\r\n            \r\n            19 - 22    500 2020-11-19 2020-11-22
#16 Jan\r\n            \r\n            21 - 24    500 2021-01-21 2021-01-24
#23   Mar\r\n            \r\n            4 - 7    550 2021-03-04 2021-03-07
#32                             Apr 29 - May 2    500 2021-04-29 2021-05-02
,

您可以尝试:

library(lubridate)
library(dplyr)

d <- do.call(rbind,lapply(str_split(gsub("[\v-]"," ",mydata$Dates),"\\s+"),function(x) if (length(x) == 3) append(x,x[1],after = 2) else x) )

start_date <- as.Date(paste(d[,1],d[,2],"2020",sep = "-"),format = "%b-%d-%Y")
end_date <- as.Date(paste(d[,3],4],format = "%b-%d-%Y")

start_date <- if_else(month(start_date) < 9,start_date + years(1),start_date)
end_date <- if_else(month(end_date) < 9,end_date + years(1),end_date)

data.frame(start_date,end_date,mydata$points)

  start_date   end_date mydata.points
1 2020-09-10 2020-09-13           500
2 2020-10-08 2020-10-11           500
3 2020-10-29 2020-11-01           500
4 2020-11-19 2020-11-22           500
5 2021-01-21 2021-01-24           500
6 2021-03-04 2021-03-07           550
7 2021-04-29 2021-05-02           500

除非您有理由不这样做,否则最好将数据保留为日期格式。但是,如果您需要它们作为显示的字符串,则可以使用format(),例如:

format(start_date,"%Y%m%d")
,

这是一个凌乱的Base R解决方案:

# Function to pad dateparts: pad_dateparts => function()
pad_dateparts <- function(date_vec){
  return(ifelse(nchar(date_vec) == 1,paste0("0",date_vec),date_vec))
}
   
# Store the months for each obersvation: months_ => list of characters
months_ <-
  lapply(regmatches(mydata$Dates,gregexpr(
    paste0(month.abb,collapse = "|"),mydata$Dates)),function(x) {
    if (length(x) == 1) {
      pad_dateparts(match(rep(x,2),month.abb))
    } else{
      pad_dateparts(match(x,month.abb))
    }
  }
)

# Store the day numbers for each obersvation: days_ => list of characters
days_ <- lapply(sapply(trimws(gsub('\\D+',' ',"both"),strsplit,pad_dateparts)

# Function to increment years from ordered vector of month parts:
# increment_years => function()
increment_years <- function(start_year,ordered_month_vec){
  return(start_year + cumsum(c(FALSE,diff(as.integer(ordered_month_vec)) < 0)))
}

# Store the year parts: years_ => list of data.frames
years_ <- split(apply(data.frame(do.call(rbind,months_)),2,function(x){increment_years(2020,x)}),seq_along(months_))
    
# Create the required data.frame: clean_df => data.frame
clean_df <- cbind(setNames(
  data.frame(
    do.call(rbind,Map(function(x,y,z) {
      as.integer(paste0(x,z))
    },years_,months_,days_)),row.names = NULL,stringsAsFactors = FALSE
  ),c("StartDate","EndDate")
),Points = mydata$points)

数据:

mydata <- structure(list(Dates = c("Sep\r\n            \r\n            10 - 13","Oct\r\n            \r\n            8 - 11","Oct 29 - Nov 1","Nov\r\n            \r\n            19 - 22","Jan\r\n            \r\n            21 - 24","Mar\r\n            \r\n            4 - 7","Apr 29 - May 2"),points = c("500","500","550","500"
)),row.names = c(1L,5L,8L,11L,16L,23L,32L),class = "data.frame")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-