簡體   English   中英

R中按組線性插值

[英]Linear interpolation by group in R

假設以下數據:

     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

對於每個組日期(為方便起見,我用點將它們區分),我想做一個簡單的線性插值:對於V1=0.08 ,我將得到什么V2

我嘗試過的方法 :首先,最合理的方法是使用approx

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

但是我卻得到了這個錯誤:

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

然后我嘗試了:

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

帶有錯誤:

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

我也嘗試了dplyr軟件包,但沒有結果:

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

這給出了錯誤:

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

謝謝。

您遇到的錯誤approx是因為使用%>%時將data.frame作為第一個參數傳遞。 因此您的通話approx(df, v1, v2, xout=0.08)

您可以在一個襯里中使用data.table完成approx調用:

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

第一次停留在tidyverse我的解決方案就沒有那么整齊; 可能有更干凈的方法可以在管道中執行此操作,但是我認為很難擊敗data.table解決方案。

強制進入magrittr管道的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM