R循环-添加没有预定义尺寸的行 [英] R Loop - Adding rows without predefined dimensions
问题描述
我想将测试结果存储在矩阵或data.frame中的R for
循环内,该矩阵或data.frame具有(在这种情况下)两列,但行数不确定,因为行数取决于if
语句.
I want to store the results of a test within an R for
loop inside a matrix or data.frame with (in this case) two columns, but an indeterminate number of rows, because the number of rows will depend on an if
statement.
我正在比较一周中几天的计数,然后进行成对比较.这是现在的代码:
I am comparing counts for days of the week, and then doing pairwise comparisons. This is the code as it stands now:
week <- c(Mon = 401, Tue = 199, Wed = 187, Thur = 202, Fri = 240, Sat = 212, Sun = 244)
names(week) <- NULL
observed <- week
for(i in 1:(length(observed) - 1)){
for(j in 1:(length(observed))){
test <- chisq.test(c(observed[i], observed[j]), p = rep(1/2, 2))
if(test$p.value < 0.002380952) print(c(i,j))
}
}
现在输出为:
[1] 1 2
[1] 1 3
[1] 1 4
[1] 1 5
[1] 1 6
[1] 1 7
[1] 2 1
[1] 3 1
[1] 4 1
[1] 5 1
[1] 6 1
但是根据函数中if
语句的结果,它可能更长.此外,我最终希望消除排列.
But depending on the results of the if
statement in the function, it could have been much longer. Further I want to ultimately erase permutations.
寻找在循环中初始化空矩阵(或data.frame)的方法,它们似乎提前合并了维度,例如在days <- matrix(NA, nrow = length(observed)^2, ncol = 2)
中.
Looking for ways to initiate an empty matrix (or data.frame) in the loop, they seem to incorporate the dimensions ahead of time, such as in days <- matrix(NA, nrow = length(observed)^2, ncol = 2)
.
相反,我希望行数不确定.
I'd like to, instead, have an indeterminate number of rows.
推荐答案
这有效:
mat <- combn(1:length(observed),2)
vec <- apply(mat, 2, function(x) chisq.test(observed[x],p=rep(1/2,2))$p.value)
mat[,c(vec < 0.002380952)]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 1 1 1 1 1
#[2,] 2 3 4 5 6 7
说明:
combn
查找数字之间的所有组合,并将它们作为矩阵返回(2
行乘n
列).然后,我们遍历n
列并找到p值.然后,我们为小于子阈值的vec
元素子集mat
.
Explanation:
combn
finds all combinations between numbers and returns them as a matrix (2
rows by n
columns). Then we go over the n
columns and find the p-values. We then subset mat
for the elements of vec
that are smaller than your threshold.
这篇关于R循环-添加没有预定义尺寸的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!