Find rows in a dataframe with a certain date using

2019-08-29 09:15发布

问题:

I have a dataframe Date , containing dates , times and values:

  Date         Time         Global_active_power
  16/12/2006   17:24:00     4.216
  16/12/2006   18:25:00     4.5
  17/12/2006   17:25:00     4.52
  18/12/2006   17:25:00     4.557

Now I want to find a row depending on the date - for example all rows with date > 16/12/2006.

This is my code:

Data$Date<- as.Date(Data$Date,"%dd%mm%yyyy" )
Data$Time<-strptime(Data$Time, "%h%m%s")
print(class(Data$Date))
print(class(Data$Time))
Data1<-subset(Data, (Date=="16/12/2006" ))
View(Data1)

the class of Date and Time were factor and factor but now they are Date and "POSIXlt" "POSIXt" . When I do the subset-command, Data1 is empty.

Why? It should contain the first 2 Datasets.

回答1:

Data$Date<- as.Date(Data$Date,"%d/%m/%Y" ) # date format now 'yyyy-mm-dd'
Data$Time <- as.POSIXct(strptime(Data$Time, "%H:%M:%S"))
print(class(Data$Date))
print(class(Data$Time))

Data1 <- subset(Data, Date > "2006-12-16") 

View(Data1)


回答2:

There's a problem with the conversion of the Time variable. Since it has no date, just a time, when you apply strptime, it will insert automatically a date, today. This is obviously not what you want. I believe that the best solution is to create a new column, DateTime.

Data$Date <- as.Date(Data$Date, "%d/%m/%Y")

# See the output date (today)
strptime(Data$Time, "%H:%M:%S")
[1] "2017-07-22 17:24:00 BST" "2017-07-22 18:25:00 BST"
[3] "2017-07-22 17:25:00 BST" "2017-07-22 17:25:00 BST"

DateTime <- paste(Data$Date, Data$Time)
DateTime
[1] "2006-12-16 17:24:00" "2006-12-16 18:25:00" "2006-12-17 17:25:00"
[4] "2006-12-18 17:25:00"

Data$DateTime <- as.POSIXct(DateTime, format = "%Y-%m-%d %H:%M:%S")

Data1 <- subset(Data, Date > as.Date("2006-12-16"))
View(Data1)

If you want to keep the data/time related variables together, you can swap columns 3 and 4.

Data <- Data[, c(1, 2, 4, 3)]
Data
        Date     Time            DateTime Global_active_power
1 2006-12-16 17:24:00 2006-12-16 17:24:00               4.216
2 2006-12-16 18:25:00 2006-12-16 18:25:00               4.500
3 2006-12-17 17:25:00 2006-12-17 17:25:00               4.520
4 2006-12-18 17:25:00 2006-12-18 17:25:00               4.557

Only then you would Data1 <- subset(...).