有没有一种简单的方法可以确定一个向量是否嵌套在另一个向量中?换句话说,在下面的示例中,每个值bar都与一个且只有一个值相关联foo,因此bar嵌套在其中foo.
data.frame(foo=rep(seq(4), each=4), bar=rep(seq(8), each=2))
Run Code Online (Sandbox Code Playgroud)
为了澄清,这是期望的结果:
foo <- rep(seq(4), each=4)
bar <- rep(seq(8), each=2)
qux <- rep(seq(8), times=2)
# using a fake operator for illustration:
bar %is_nested_in% foo # should return TRUE
qux %is_nested_in% foo # should return FALSE
Run Code Online (Sandbox Code Playgroud)
假设你有两个因素f和g,并想知道是否g嵌套在f.
方法1:对于喜欢线性代数的人
考虑两个因素的设计矩阵:
Xf <- model.matrix(~ f + 0)
Xg <- model.matrix(~ g + 0)
Run Code Online (Sandbox Code Playgroud)
如果g嵌套在f,则列空间Xf必须是列空间的子空间Xg.换句话说,对于Xf列的任何线性组合:y = Xf %*% bf,Xg %*% bg = y可以精确地求解方程.
y <- Xf %*% rnorm(ncol(Xf)) ## some random linear combination on `Xf`'s columns
c(crossprod(round(.lm.fit(Xg, y)$residuals, 8))) ## least squares residuals
## if this is 0, you have nesting.
Run Code Online (Sandbox Code Playgroud)
方法2:对于喜欢统计数据的人
我们检查列联表:
M <- table(f, g)
Run Code Online (Sandbox Code Playgroud)
如果所有列只有一个非零条目,则g嵌套f.换一种说法:
all(colSums(M > 0L) == 1L)
## `TRUE` if you have nesting
Run Code Online (Sandbox Code Playgroud)
注释:对于任何方法,您都可以轻松地将代码压缩到一行.
| 归档时间: |
|
| 查看次数: |
658 次 |
| 最近记录: |