2016-01-20 68 views
1

我需要從5年的時間間隔內插年度數據,到目前爲止,我發現如何使用approx()實現一次觀察。但是我有一個大的數據集,當試圖使用ddply()來申請每一行時,無論我在最後一行代碼中嘗試什麼,我都會收到錯誤消息。(線性)R中插值數據幀(ddply)

e.g:

town <- data.frame(name = c("a","b","c"), X1990 = c(100,300,500), X1995=c(200,400,700)) 
    d1990 <-c(1990) 
    d1995 <-c(1995) 
    town_all <- cbind(town,d1990,d1995) 


    library(plyr) 
    Input <- data.frame(town_all) 
    x <- c(town_all$X1990, town_all$X1995) 
    y <- c(town_all$d1990, town_all$d1995) 
    approx_frame <- function(df) (approx(x=x, y=y, method="linear", n=6, ties="mean")) 
    ddply(Input, town_all$X1990, approx_frame) 

另外,如果你知道什麼函數計算幾何插值,這將是巨大的。 (我只能找到樣條或常量方法的例子。)

回答

1

我首先把數據放在長格式中(每列對應一個變量,所以一列'年'和'值'一列) 。然後,我使用data.table,但dplyr或另一個拆分應用組合方法可以遵循相同的方法。這個interp功能是爲了對每個間隔計算恆定的速率進行幾何插值。

## Sample data (added one more year) 
towns <- data.frame(name=c('a', 'b', 'c'), 
        x1990=c(100, 300, 500), 
        x1995=c(200, 400, 700), 
        x2000=c(555, 777, 999)) 

## First, transform data from wide -> long format, clean year column 
library(data.table)              # or use reshape2::melt 
towns <- melt(as.data.table(towns), id.vars='name', variable.name='year') # wide -> long 
towns[, year := as.integer(sub('[[:alpha:]]', '', year))]      # convert years to integers 

## Function to interpolate at constant rate for each interval 
interp <- function(yrs, values) { 
    tt <- diff(yrs)    # interval lengths 
    N <- head(values, -1L)  
    P <- tail(values, -1L) 
    r <- (log(P) - log(N))/tt # rate for interval 
    const_rate <- function(N, r, time) N*exp(r*(0:(time-1L))) 
    list(year=seq.int(min(yrs), max(yrs), by=1L), 
     value=c(unlist(Map(const_rate, N, r, tt)), tail(P, 1L))) 
} 

## geometric interpolation for each town 
res <- towns[, interp(year, value), by=name] 

## Plot 
library(ggplot2) 
ggplot(res, aes(year, value, color=name)) + 
    geom_line(lwd=1.3) + theme_bw() + 
    geom_point(data=towns, cex=2, color='black') + # add points interpolated between 
    scale_color_brewer(palette='Pastel1') 

enter image description here

+0

那完美。謝謝! – user5818045