3

合計 500 列の次のようなデータ フレームがあります。

Probes <- data.frame(Days=seq(0.01, 4.91, 0.01), B1=5:495,B2=-100:390, B3=10:500,B4=-200:290)

ウィンドウ サイズが 12 データ ポイントで、各逐次回帰が 6 データ ポイントで区切られているローリング ウィンドウ線形回帰を計算したいと思います。各回帰では、「日」は常にモデルの x コンポーネントになり、y は他の各列 (B1、その後に B2、B3 など) になります。次に、係数を既存の列タイトル (B1、B2 など) とともにデータフレームとして保存したいと思います。

私のコードは近いと思いますが、うまく機能していません。Zoo Library の rollapply を使用しました。

slopedata<-rollapply(zoo(Probes), width=12, function(Probes) { 
 coef(lm(formula=y~Probes$Days, data = Probes))[2]
 }, by = 6, by.column=TRUE, align="right")

可能であれば、「xmins」をベクターに保存してデータフレームに追加したいと思います。これは、各回帰で使用される最小の x 値を意味します (基本的には、「日」列の 6 つの数値ごとになります)。ご協力ありがとうございます。

4

3 に答える 3

2

1)zデータが含まれProbes、プローブの最初の列からインデックスが取得される動物園オブジェクトを定義しますDays。回帰係数を計算する関数を行列として定義lmできることに注意してください。ついに終わった。返されたオブジェクトのインデックスが xmin を与えることに注意してください。ycoefsrollapplyz

library(zoo)

z <- zoo(Probes, Probes[[1]])

coefs <- function(z) c(unlist(as.data.frame(coef(lm(z[,-1] ~ z[,1])))))
rz <- rollapply(z, 12, by = 6, coefs, by.column = FALSE, align = "left")

与える:

> head(rz)
     B11 B12  B21 B22 B31 B32  B41 B42
0.01   4 100 -101 100   9 100 -201 100
0.07   4 100 -101 100   9 100 -201 100
0.13   4 100 -101 100   9 100 -201 100
0.19   4 100 -101 100   9 100 -201 100
0.25   4 100 -101 100   9 100 -201 100
0.31   4 100 -101 100   9 100 -201 100

DF <- fortify.zoo(rz)のデータ フレーム表現が必要な場合に使用できることに注意してくださいrz

2)やや似た別のアプローチはrollaplly、行番号を超えることです。

library(zoo)
y <- as.matrix(Probes[-1])
Days <- Probes$Days
n <- nrow(Probes)
coefs <- function(ix) c(unlist(as.data.frame(coef(lm(y ~ Days, subset = ix)))), 
      xmins = Days[ix][1])
r <- rollapply(1:n, 12, by = 6, coefs)
于 2015-11-19T22:10:17.260 に答える
0

これを試して:

# here are the xmin values you wanted
xmins <- Probes$Days[seq(1,nrow(Probes),6)]

# here we build a function that will run regressions across the columns
# y1 vs x, y2 vs x, y3 vs x...
# you enter the window and by (12/6) in order to limit the interval being
# regressed. this is later called in do.call
runreg <- function(Probes,m,window=12,by=6){

  # beg,end are used to specify the interval
  beg <- seq(1,nrow(Probes),by)[m]
  end <- beg+window-1

  # this is used to go through all the columns
  N <- ncol(Probes)-1
  tmp <- numeric(N)
  # go through each column and store the coefficients in tmp
  for(i in 1:N){
     y <- Probes[[i+1]][beg:end]
     x <- Probes$Days[beg:end]
     tmp[i] <- coef(lm(y~x))[2][[1]]
  }
  # put all our column regressions into a dataframe
  res <- rbind('coeff'=tmp)
  colnames(res) <- colnames(Probes)[-1]

  return(res)
}

# now that we've built the function to do the column regressions
# we just need to go through all the window-ed regressions (row regressions)
res <- do.call(rbind,lapply(1:length(xmins),function(m) runreg(Probes,m)))

# these rownames are the index of the xmin values
rownames(res) <- seq(1,nrow(Probes),6)
res <- data.frame(res,xmins)
于 2015-11-19T21:27:48.647 に答える