-2

I have a problem with two vectors with different lengths. I would like realise the subtraction between the values of the two vectors where the time is the same.

For example:

theo <- data.frame(
    time = seq(236.4, 850, by = 0.01), 
    val = seq(0, 6136, 0.1)
)
obs <- data.frame(
    time = c(260.76, 270.53, 288.44, 308.15,
             310.12, 319.38, 335.25), 
    val = c(1, 8, 10, 5, 0.2, 6, 5)
)

I tried

 with(theo[theo$time==obs$time,],sum((obs$val -theo$val)^2))

But that didn't work.

nrussell
  • 18,382
  • 4
  • 47
  • 60
Marambo
  • 57
  • 2
  • 7
  • @jogo Read the question again. Merging is the last option I'd consider here, that's serious overkill. – Joris Meys Feb 23 '17 at 14:01
  • @JorisMeys I read the question again, but I can not find any information that excludes the solution with `merge()`. – jogo Feb 23 '17 at 15:00
  • @jogo maybe the part where the requested object is a single value, not a data frame? – Joris Meys Feb 23 '17 at 15:21

1 Answers1

1

Use indices. And the call to with() is absolutely unnecessary. You only use that when you want to do operations with different variables of the same data frame. In your code you work with 2 different data frames.

This code does give you what you want. I had to take floating point errors into account, which actually took me by surprise. That's why I had to use round()

id <- match(round(obs$time,2), round(theo$time,2)
sum(obs$val - theo$val[id])^2
Joris Meys
  • 106,551
  • 31
  • 221
  • 263