【问题标题】:Subset data with the date format "01.01.2009 08:00:00, 01.01.2009 9:00:00, ..."日期格式为“01.01.2009 08:00:00, 01.01.2009 9:00:00, ...”的子集数据
【发布时间】:2020-07-05 04:54:11
【问题描述】:

我目前正在尝试对我的数据集中的数据进行子集化。我使用了dputstr,所以你可以看到我正在使用什么:

dput

structure(list(Date = structure(1:10, .Label = c("01.01.2009 00:00:00", 
"01.01.2009 01:00:00", "01.01.2009 02:00:00", "01.01.2009 03:00:00", 
"01.01.2009 04:00:00", "01.01.2009 05:00:00", "01.01.2009 06:00:00", 
"01.01.2009 07:00:00", "01.01.2009 08:00:00", "01.01.2009 09:00:00"
), class = "factor"), SWC = c(NaN, NaN, NaN, NaN, NaN, NaN, NaN, 
NaN, NaN, NaN)), row.names = c(NA, 10L), class = "data.frame")

str

'data.frame':   8756 obs. of  2 variables:
 $ Date: Factor w/ 96408 levels "01.01.2009 00:00:00",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ SWC : num  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ...

如您所见,我的日期格式为“DD MM YY HH MM SS”。为了对我的数据进行子集化,我尝试使用 subset() 函数(见下文)。

Mois2009_2 <- subset(Mois1$Date <= "31.12.2009 23:00:00") 

但我收到以下错误:

In Ops.factor(Mois1$Date, "31.12.2009 23:00:00") :
      ‘<=’ not meaningful for factors

我查看了错误,发现我必须使用转换我的日期

as.Date(Mois1$Date)

这产生了另一个错误,上面写着:

Character string is not in a unique standard format.

我刚开始使用 R,希望能得到一些帮助!

【问题讨论】:

  • Phil 一旦您将数据转换为日期,假设它被正确解释,那么您还需要使用标准 iso 日期格式的过滤条件。那是 "2009-12-31 23:00:00" 。对数据进行子集化的更简单方法是使用 grepl 函数。 grepl 在字符串中查找字符串,例如“2009”。所以my_list_object[grepl("2009", my_list_object)] 会让你得到你想要的。

标签: r date subset


【解决方案1】:

你可以这样解决:

Mois1 <- structure(list(Date = structure(1:10, .Label = c("01.01.2009 00:00:00", 
                   "01.01.2009 01:00:00", "01.01.2009 02:00:00", "01.01.2009 03:00:00", 
                   "01.01.2009 04:00:00", "01.01.2009 05:00:00", "01.01.2009 06:00:00", 
                   "01.01.2009 07:00:00", "01.01.2009 08:00:00", "01.01.2009 09:00:00"
                   ), class = "factor"), SWC = c(NaN, NaN, NaN, NaN, NaN, NaN, NaN, 
                   NaN, NaN, NaN)), row.names = c(NA, 10L), class = "data.frame")

Mois1$Date <- as.Date(Mois1$Date, format = "%d.%m.%Y %H:%M:%S")
Mois2009_2 <- subset(Mois1, Date <= "2009-12-31 23:00:00")

【讨论】:

    【解决方案2】:

    我们可以从dplyr使用filter

    library(dplyr)
    library(lubridate)
    df1 %>%
        filter(dmy_hms(Date) <= "2009-12-31 23:00:00")
    

    【讨论】:

    • @SKyJim 我尝试使用 grepl():M2009 &lt;- Mois1[grepl("2009", Mois1)] 但这只会返回整个数据集,并且不仅包含其中包含“2009”的值。我查找了包含日期的列的模式,它显示“数字”,所以我也认为在这里查找字符没有帮助。
    • 如果我输入 Mois1%&gt;% filter(dmy_hms(Date) &lt;= "2009-12-31 23:00:00") 它会说:找不到函数 %>%
    • @B. Christian Kamgang 非常感谢,这很有效!但是我现在确实有问题,因为现在列中缺少时间。你知道如何解决这个问题吗?
    • @Phil 也许你想对其他帖子发表评论?
    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多