[英]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)
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.