1

I want to add one minute to the timestamp of specific cases. Say I have

timestamp <- seq(
  from = as.POSIXct("12/05/2017 9:00", format = "%m/%d/%Y %H:%M"), 
  by = 60, 
  to = as.POSIXct("12/05/2017 9:02", format = "%m/%d/%Y %H:%M"))   
ID <- seq(from = 101, by = 1, to = 115)
df <- data.frame(ID, timestamp)

To apply to a list of cases, I tried the following:

vars <- list(101, 102, 103)

foo <- function(x) { 
  as.POSIXct(df$encounter[dat$ID == x], 
  format = "%m/%d/%Y %H:%M") + 60     
}

lapply(vars, foo)

which returns the correct responses in a list, but I am not able to coerce the results to a data frame so they can be added to the original file. I found this solution here for returning a data frame,

results <- lapply(vars, foo)
as.data.frame(do.call(rbind, results))

but it returns the timestamp as an unformatted numeric object. I tried indexing by case number

as.POSIXct(df$timestamp, format = "%m/%d/%Y %H:%M")[df$ID == 101] + 60

which prints the correct result to the screen, but I cannot figure out the correct syntax to replace the value(s) in the data frame itself.

votmoyd
  • 65
  • 8

2 Answers2

0

I will create a new column to show the difference. but you can just replace on top.

transform(dat,a=strptime(timestamp,"%m/%d/%Y %H:%M")+60)
       ID      timestamp                   a
    1 123 12/4/2017 6:00 2017-12-04 06:01:00
    2 456 12/5/2017 7:00 2017-12-05 07:01:00
    3 789 12/6/2017 8:00 2017-12-06 08:01:00

if you need to format it back to your data:

transform(dat,timestamp=format(strptime(timestamp,"%m/%d/%Y %H:%M")+60,"%m/%d/%Y %H:%M"))
   ID        timestamp
1 123 12/04/2017 06:01
2 456 12/05/2017 07:01
3 789 12/06/2017 08:01

Data:

dat=read.table(text="ID    timestamp
123   '12/4/2017 6:00'
               456   '12/5/2017 7:00'
               789   '12/6/2017 8:00'",h=T,strings=F)
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Thank you. This solution works for the whole data set, but I need to apply to a list of specific cases. I edited the post after your comment, to be more clear. – votmoyd Apr 24 '18 at 19:43
0

You can use replace.

ind <- which(ID %in% c(101, 102, 103))
df$timestamp <- with(df, 
                     replace(timestamp
                            , ind
                            , timestamp[ind] + 60))

In tidyverse, you can use case_when.

library(tidyverse)
df <- df %>% 
        mutate(timestamp = case_when(ID %in% c(101, 102, 103) ~ timestamp + 60,
                                      T ~ timestamp))
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38