2

Suppose the following data:

     Date        V1              V2
1 1996-01-04 0.04383562 days 0.1203920
2 1996-01-04 0.12054795 days 0.1094760
..............
3 1996-02-01 0.04383562 days 0.1081815
4 1996-02-01 0.12054795 days 0.1092450
..............
5 1996-03-01 0.04109589 days 0.1553875
6 1996-03-01 0.13687215 days 0.1469690

For each of the group dates (which i distinguished them by dots for ease), i want to do a simple linear interpolation: for a V1=0.08 what V2 i will get.

What I have tried: first the most logical approach to use approx:

IV<-data %>% group_by(Date) %>% approx(V1,V2,xout=0.08)

but instead i get this error:

Error in approx(., V1, V2, xout = 0.08) : 
  invalid interpolation method
In addition: Warning message:
In if (is.na(method)) stop("invalid interpolation method") :
  the condition has length > 1 and only the first element will be used

then i tried:

Results<-unsplit(lapply(split(data,data$Date),function(x){m<-lm(V2~V1,x)
                                                       cbind(x,predict(m,0.08))}),data$Date)

with an error:

Error in model.frame.default(formula = x[, 3] ~ x[, 2], data = x, drop.unused.levels = TRUE) : 
  invalid type (list) for variable 'x[, 3]'

I also tried the dplyr package with no results:

IV<-data %>% group_by(Date) %>% predict(lm(V2~V1,data=data,0.08)

which gave the error:

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "c('grouped_df', 'tbl_df', 'tbl', 'data.frame')"

Thank you.

duplode
  • 33,731
  • 7
  • 79
  • 150
Hercules Apergis
  • 423
  • 6
  • 20

1 Answers1

4

The error you were getting in approx is because you are passing the data.frame as the first argument when using %>%. so your call is approx(df, v1, v2, xout=0.08).

You could accomplish the approx call using data.table in a one liner:

library(data.table)
#created as df instead of dt for use in dplyr solution later
df <- data.frame(grp=sample(letters[1:2],10,T),
             v1=rnorm(10),
             v2=rnorm(10))

dt <- data.table(df)

dt[, approx(v1,v2,xout=.08), by=grp]

#output
   grp    x          y
1:   b 0.08 -0.5112237
2:   a 0.08 -1.4228923

On a first pass to stay in the tidyverse my solution isnt so tidy; there is likely a cleaner way to do this in a pipeline, but i think it'll be hard to beat the data.table solution.

Solution forced into magrittr pipeline:

library(dplyr)

df %>% 
    group_by(grp) %>% 
    summarise(out=list(approx(v1,v2,xout=.08))) %>% 
    ungroup() %>% 
    mutate(x=purrr::map_dbl(out,'x'),
           y=purrr::map_dbl(out,'y')) %>% 
    select(-out)

#output
# A tibble: 2 × 3
     grp     x          y
  <fctr> <dbl>      <dbl>
1      a  0.08 -1.4228923
2      b  0.08 -0.5112237
Adam Spannbauer
  • 2,707
  • 1
  • 17
  • 27
  • 1
    Sorry for the late reply, but approx doesn't work well (returns NA) when I extrapolate, is that correct? It works perfectly for the interpolation part. – Hercules Apergis May 15 '17 at 09:50