R Loop - Adding rows without predefined dimensions -


i want store results of test within r for loop inside matrix or data.frame (in case) 2 columns, but indeterminate number of rows, because number of rows depend on if statement.

i comparing counts days of week, , doing pairwise comparisons. code 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))    } } 

the output now:

[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 

but depending on results of if statement in function, have been longer. further want erase permutations.

looking ways initiate empty matrix (or data.frame) in loop, seem incorporate dimensions ahead of time, such in days <- matrix(na, nrow = length(observed)^2, ncol = 2).

i'd to, instead, have indeterminate number of rows.

this works:

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 

explanation: combn finds combinations between numbers , returns them matrix (2 rows n columns). go on n columns , find p-values. subset mat elements of vec smaller threshold.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -