Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. Date V1 V2
  2. 1 1996-01-04 0.04383562 days 0.1203920
  3. 2 1996-01-04 0.12054795 days 0.1094760
  4. ..............
  5. 3 1996-02-01 0.04383562 days 0.1081815
  6. 4 1996-02-01 0.12054795 days 0.1092450
  7. ..............
  8. 5 1996-03-01 0.04109589 days 0.1553875
  9. 6 1996-03-01 0.13687215 days 0.1469690
  10.  
  11. IV<-data %>% group_by(Date) %>% approx(V1,V2,xout=0.08)
  12.  
  13. Error in approx(., V1, V2, xout = 0.08) :
  14. invalid interpolation method
  15. In addition: Warning message:
  16. In if (is.na(method)) stop("invalid interpolation method") :
  17. the condition has length > 1 and only the first element will be used
  18.  
  19. Results<-unsplit(lapply(split(data,data$Date),function(x){m<-lm(V2~V1,x)
  20. cbind(x,predict(m,0.08))}),data$Date)
  21.  
  22. Error in model.frame.default(formula = x[, 3] ~ x[, 2], data = x, drop.unused.levels = TRUE) :
  23. invalid type (list) for variable 'x[, 3]'
  24.  
  25. IV<-data %>% group_by(Date) %>% predict(lm(V2~V1,data=data,0.08)
  26.  
  27. Error in UseMethod("predict") :
  28. no applicable method for 'predict' applied to an object of class "c('grouped_df', 'tbl_df', 'tbl', 'data.frame')"
  29.  
  30. library(data.table)
  31. #created as df instead of dt for use in dplyr solution later
  32. df <- data.frame(grp=sample(letters[1:2],10,T),
  33. v1=rnorm(10),
  34. v2=rnorm(10))
  35.  
  36. dt <- data.table(df)
  37.  
  38. dt[, approx(v1,v2,xout=.08), by=grp]
  39.  
  40. #output
  41. grp x y
  42. 1: b 0.08 -0.5112237
  43. 2: a 0.08 -1.4228923
  44.  
  45. library(dplyr)
  46.  
  47. df %>%
  48. group_by(grp) %>%
  49. summarise(out=list(approx(v1,v2,xout=.08))) %>%
  50. ungroup() %>%
  51. mutate(x=purrr::map_dbl(out,'x'),
  52. y=purrr::map_dbl(out,'y')) %>%
  53. select(-out)
  54.  
  55. #output
  56. # A tibble: 2 × 3
  57. grp x y
  58. <fctr> <dbl> <dbl>
  59. 1 a 0.08 -1.4228923
  60. 2 b 0.08 -0.5112237
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement