Ben Ben - 17 days ago 5
R Question

How to add a time to given columns in a dataframe

I have a dataframe with several columns. The odd columns contain the time series, the even columns the data:

time1.in.s <- seq(0.010, 100, length.out = 100)
time2.in.s <- seq(0.022, 100, length.out = 100)
data1 <- seq(-10, 100, length.out = 100)
data2 <- seq(-25, 80, length.out = 100)

my.df <- data.frame(time1.in.s, data1, time2.in.s, data2)


(In real life, I have more columns).

Now the time is the odd columns is relative, in seconds.

I want to add a given start time to all the time values:

start.time <- strptime("2016-11-22_15-44-24",
format = "%Y-%m-%d_%H-%M-%S",
tz = "UTC")


I know how to select the odd columns:

odd.indexes <- seq(1, ncol(my.df), 2)


But to add the start time to the relative times, I did something naïve...

my.df[, odd.indexes] <- start.time + my.df[, odd.indexes]


... which doesn't work:


Error in start.time + my.df[, odd.indexes] :
non-numeric argument
to binary operator

In addition: Warning message: Incompatible methods
("+.POSIXt", "Ops.data.frame") for "+"


How to make it work ?

Answer

We need to loop over the columns and then do the +

my.df[, odd.indexes] <- lapply(my.df[, odd.indexes], `+`, start.time)