Home > OS >  How to filter a part of dates and then change that part?
How to filter a part of dates and then change that part?

Time:01-03

There are a group of dates in test_2 called df that I'm trying to change. For example: 2020-12-15 is in the started_at column and 2020-12-25 is in the ended_at column. I want to change the daypart of the ended_at column.

I could write day(test_2$ended_at) <- 15 #[thanks Ben for guiding me with this chunk]

But the problem is there are some other days also. Like, 2020-12-08 etc.

How is it possible to filter the required part of the date and change it? I soulfully appreciate your kind help.

Here is the dput of the data structure.

> dput(test_2)  
structure(list(started_at = structure(c(1608033433, 1608033092, 
1608033242, 1608034138, 1608034548, 1608033904, 1608033525, 1608032413, 
1608032432, 1607385918, 1608032241, 1608034867, 1609079592, 1608033139, 
1608032406, 1608034912, 1608033844, 1608032114, 1608034239, 1608032677, 
1608032219, 1608033975, 1609459101, 1608032929, 1608034558, 1608034138, 
1608033654, 1608033875, 1606810523, 1608034878, 1608034232), tzone = "UTC", class = c("POSIXct", 
"POSIXt")), ended_at = structure(c(1608914839, 1608908027, 1608909124, 
1608924913, 1608905112, 1608920814, 1608915081, 1608891612, 1608896054, 
1607385667, 1608891462, 1608922015, 1606985651, 1608907113, 1608896350, 
1608923619, 1608923486, 1608887393, 1608934063, 1608899164, 1608886816, 
1608924042, 1606781193, 1608907025, 1608914882, 1608923510, 1608921699, 
1608922845, 1606810492, 1608913874, 1608943331), tzone = "UTC", class = c("POSIXct", 
"POSIXt"))), row.names = c(NA, -31L), class = c("tbl_df", "tbl", 
"data.frame"))

CodePudding user response:

Based on the description, we may create a logical index for subsetting and updating the 'ended_at' column

library(lubridate)
i1 <- with(test_2, as.Date(started_at) == "2020-12-15" & 
        as.Date(ended_at ) == "2020-12-25")
day(test_2$ended_at[i1]) <- 15
  •  Tags:  
  • r
  • Related