2

I have a data frame including a motion signal sampled at 100Hz. In a simplified way it looks like this:

df<-data.frame(c(0.01, 0.02, 0.05, 0.06), c(0, 0, 2, 0), c(2,3,10,15))
names(df)<-c("counter", "lostSamples", "value")
df
#   counter lostSamples value
# 1    0.01           0     2
# 2    0.02           0     3
# 3    0.05           2    10
# 4    0.06           0    15

counter” is each sample; “lostSamples” is when my device could not record/store the sample; “value” is the actual signal in 1 dimension relative to a reference

I would like to add rows when there are lost samples. In this example I have to fill the gap (add rows to data frame) for counters 0.3 and 0.4. I would like to fill the gaps either with NAs (easier) or interpolating by a linear function depending on values before and after the gap.

I tried with for loops and with apply but was not successful.

0

2 Answers 2

2

This could be another way

df2 = data.frame(counter = seq(0.01, 0.06, 0.01))
out = merge(df, df2, all = T)

#  counter lostSamples value
#1    0.01           0     2
#2    0.02           0     3
#3    0.03          NA    NA
#4    0.04          NA    NA
#5    0.05           2    10
#6    0.06           0    15
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, simple approach, though you would need to be careful about floating point rounding issues here.
@josilber yes you are right! I like the use of approx in your answer.
1

If you have the list of expected values for the counter, you can do this with the approx function for linear interpolation:

expected <- seq(0.01, 0.06, 0.01)
data.frame(counter=expected,
           value=approx(df$counter, df$value, expected)$y)
#   counter     value
# 1    0.01  2.000000
# 2    0.02  3.000000
# 3    0.03  5.333333
# 4    0.04  7.666667
# 5    0.05 10.000000
# 6    0.06 15.000000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.