Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

How can I extract a specific range of hours from a dataframe in R

I have a data frame in R with 2 columns (date_time , temp) I want to extract all the temp for the day time (between 5:59 Am to 18:00 Pm). I firstly separated date and times(hours) with this code:

Th$Hours <- format(as.POSIXct(Th$`date`,
"%Y-%m-%d %H:%M:%S", tz = ""),
format = "%H:%M")%>% as_tibble()

Th$Dates <- format(as.Date(Th$`date`,"%Y-%m-%d",
tz = ""), format = "%Y-%m-%d")%>% as_tibble()

and then I use following command to extract specific times:

Th_day<- Th[Th$Hours >= " 06:00 AM" & Th$Hours<= "18:00 PM",]%>% as_tibble()

But I get a tibble that give rows from 00:00 to 18:00 for every day :

What is the problem ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't separate out the date from the time. When you use format to get the time, you are converting it to a character class, that doesn't know how to do time-based comparisons with > and <.

Instead, use hour to extract the hour component as an integer, and do comparisons on that:

library(lubridate)
Th %>% 
  mutate(DateTime <- as.POSIXct(date, "%Y-%m-%d %H:%M:%S", tz = "")) %>%
  filter(hour(DateTime) >= 6 & hour(DateTime ) < 18)

I'm making some assumptions about your data structure - if you need more help than this please edit your question to share some sample data with dput() as the commenters have requested. dput(Th[1:5, ]) should be plenty.

Note that if you want to do a lot of operations on just the times (ignoring the date part), you could use the times class from the chron package, see here for some more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...