【问题标题】:How to show the Date Range using R如何使用 R 显示日期范围
【发布时间】:2015-12-23 03:06:27
【问题描述】:

我对使用R 非常陌生。我正在尝试用数据集做一些基本的事情。我有一个只有一列 (date) 的数据集,其中包含参与者填写调查的日期:

11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
27/11/2015
27/11/2015
etc (there are about 180 more responses)

到目前为止我已经完成了:

NUdates <- nrow(unique(date)) 

这表明我有 12 个基于响应的唯一日期

接下来我要做的就是只返回最早和最晚的日期,这样我就会有对象:

Emonth # (this would be the earliest month that a participant filled out the survey)
Lmonth # (this would be the latest month that a participant filled out he survey)
Year   # (this would be the year the surveys were filled out)

然后使用降价我可以说:

参与者在r (Emonth)r (Lmonth) 之间的r (NUdates) 天完成了r (year) 的调查。

【问题讨论】:

  • 我怀疑?range 函数会在这里剪掉它。你试过?min?max 吗?
  • Nope range 函数不起作用,至少在日期格式中不起作用,min max 也不起作用,原因相同:FUN(X[[i ]], ...) : 仅在具有所有数值变量的数据框上定义
  • 尝试用 as.date 包裹它。看我可以帮你解决你的问题,但你需要为我们提供一个可重现的例子。我们没有时间在这里猜测您的数据并手动创建变量。所以在你问问题之前,请阅读规则。
  • 函数名是as.Date

标签: r r-markdown


【解决方案1】:
txt <- "11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
11/11/2015
27/11/2015
27/11/2015"

> dates <- as.Date(scan(text=txt, what=""), format="%d/%m/%Y")

Read 10 items
> dates
 [1] "2015-11-11" "2015-11-11" "2015-11-11" "2015-11-11" "2015-11-11"
 [6] "2015-11-11" "2015-11-11" "2015-11-11" "2015-11-27" "2015-11-27"
)

要获取 Date 类对象之间的差异,可以使用 - 运算符。

>  max(dates) - min(dates) 
Time difference of 16 days

要删除多余的材料,您可以使用unclass

dput(max(dates) - min(dates))
structure(0, units = "days", class = "difftime")

unclass(max(dates) - min(dates))
[1] 16
attr(,"units")
[1] "days"

【讨论】:

  • 感谢您的帮助,正是我所需要的。我曾尝试使用 as.Date 函数,但错误地指定了格式。非常感谢。
【解决方案2】:

此答案假设您在序列中找到了您的唯一日期。 后续步骤 -
1) 确保您的日期按排序顺序排列。你可以这样做 -

table <- table[order(table$Date),]

table 是您唯一日期的数据框。

2)使用包timeDate
函数 timeFirstDayInMonth() 和 timeLastDayInMonth() 是您需要的。

start_date <- timeFirstDayInMonth(table$Date[1])                #First Date Of First Occuring Month
end_date <- timeLastDayInMonth(table$Date[nrow(table)-1])       #Last Date Of Last Occuring Month

3) 你终于可以找到 Emonth 和 Lmonth

Emonth <- format(start_date, format = "%B")        #Full Month name

Lmonth <- format(end_date, format = "%m")        #Decimal Month

【讨论】:

    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多