简体   繁体   English

从包含 model 观测值的数据帧列表构建设计矩阵

[英]Construct a design matrix from list of data frames contain the model obervation

# Construct a design matrix
# model y = y0 +y1.t + y2. cos(t) + y3 + y4 + y5
 # unknowns are y0, y1, y2, y3, y4, y5 
# where y3, y4, y5 corresponds to three instruments A, B, C
# Data 
dat <- list("A" = data.frame(t=c(1,5), var= "A"),
            "B" = data.frame(t= c(7,4,1), var= "B"),
            "C" = data.frame(t= c(12,4,3,9), var= "C"))

design_mat <-lapply(dat, function(x) {matrix(c(rep(1,nrow(x)), x$t,
                       cos(x$t), rep(1,nrow(x)), rep(0,nrow(x)), rep(0,nrow(x))), ncol=6)})

design_mat <- do.call(rbind.data.frame, design_mat)

The above code gives the following result上面的代码给出了以下结果在此处输入图像描述

the desired result is as follows期望的结果如下在此处输入图像描述

We could use table我们可以使用table

out <- cbind(V1 = 1, do.call(rbind, dat))
out$V3 <- cos(out$t)
out <- cbind(out, as.data.frame.matrix( table(seq_len(nrow(out)), out$var)))

model.matrix can also be handy when constructing design matrices. model.matrix在构造设计矩阵时也很方便。

design_mat <-lapply(dat, function(x) data.frame(v1 = x$t,v2 = cos(x$t),v3 = x$var))
tmp <- do.call(rbind,(design_mat))
cbind(model.matrix(v2 ~ v3, tmp),tmp)

    (Intercept) v3B v3C v1         v2 v3
A.1           1   0   0  1  0.5403023  A
A.2           1   0   0  5  0.2836622  A
B.1           1   1   0  7  0.7539023  B
B.2           1   1   0  4 -0.6536436  B
B.3           1   1   0  1  0.5403023  B
C.1           1   0   1 12  0.8438540  C
C.2           1   0   1  4 -0.6536436  C
C.3           1   0   1  3 -0.9899925  C
C.4           1   0   1  9 -0.9111303  C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM