Reputation: 6741
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 ?
Upvotes: 1
Views: 375
Reputation: 23099
The following should also work (slight modification of what you are doing):
my.df[, odd.indexes] <- as.data.frame(start.time + as.matrix(my.df[, odd.indexes]))
Upvotes: 1
Reputation: 887213
We need to loop over the columns and then do the +
my.df[, odd.indexes] <- lapply(my.df[, odd.indexes], `+`, start.time)
Upvotes: 1