如何将一系列日期更改为一个日期R?

时间:2019-01-19 20:18:59

标签: r dataframe matrix

我有一个民意测验的数据帧,其一列的标题为Date.s.administered,格式为一个字符串,其中包含进行民意测验的日期。例如,"January 16-20, 2019""December 1-11, 2018"。整个列如下所示:

[1] "November 3–5, 2018"    "November 1–2, 2018"   
[3] "October 28–30, 2018"   "October 22–28, 2018"  
[5] "October 15–28, 2018"   "October 15–28, 2018"  
[7] "October 25–26, 2018"   "October 18–21, 2018"  
[9] "October 15–21, 2018"   "October 12–18, 2018"  
[11] "October 10–14, 2018"   "October 9–13, 2018"   
[13] "October 9–13, 2018"    "October 8–13, 2018"   
[15] "October 8–11, 2018"    "October 3–9, 2018"    

如何处理此列,使其仅显示系列的最后日期(例如,"March 1-4, 2018"变为"March 4, 2018")?

3 个答案:

答案 0 :(得分:2)

您可以这样做:

Bootstrap: https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

CSS:
body {
  font-family: Arial, Helvetica, sans-serif;
}

.modal {
  display: block;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.8);
}

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 60%;
  min-height: 35px;
}

示例数据:

gsub("\\d+–", "", df$Date.s.administered)

输出:

df <- data.frame(Date.s.administered = c("November 3–5, 2018", "November 1–2, 2018"))

答案 1 :(得分:0)

您可以结合使用lubridate包和正则表达式来提取字符串模式,然后转换为标准日期字段。

suppressPackageStartupMessages(library(lubridate))

x <- "March 1-4, 2018"

mdy(gsub("(^.+)(\\s\\d-)(\\d)(,\\s)(\\d{4}$)", '\\1 \\3 \\5', x))
#> [1] "2018-03-04"

答案 2 :(得分:0)

使用input[type="number"] { -moz-appearance: textfield; } 的方法可能是:

tidyverse

首先,它基于“ –”将“ date”列分为“ date1”和“ date2”,然后,仅保留“ date1”中的字母,并将其与“ date2”组合成所需的“ date”列。

样本数据:

date %>%
 separate(date, c("date1", "date2"), sep = "–") %>%
 mutate(date = paste(sub("[^[:alpha:]]+", "", date1), date2, sep = " ")) %>%
 select(date)

              date
1 November 2, 2018
2 October 28, 2018
3 October 28, 2018