mercredi 13 juin 2018

How to avoid for loops using ifelse on every row of a matrix

I'm very new to R, so I'm not sure what to do here. I want to use my random matrix to check if certain answers in certain rows were chosen. Then I want to use ifelse on every combination of the different rows. I tried for statements, but it takes a very long time and I don't even think it's giving me what I want. I want to know how many have none of these answers, how many have some of these answers, how many have all of these answers, etc.

tests=matrix(sample(letters[1:5],333120,replace=T),32,10410)

t3=tests[3,] %in% c("b","c")
t4=tests[4,] %in% c("b","c","d")
t7=tests[7,] %in% c("a","b","c")
t8=tests[8,] %in% c("b","c","d")
t12=tests[12,] %in% c("a","b","d")
t13=tests[13,] %in% c("a","b","e")
t17=tests[17,] %in% c("b","c","e")
t18=tests[18,] %in% c("c","d","e")
t24=tests[24,] %in% c("b","c","d")

uncommontests=matrix(cbind(t3,t4,t7,t8,t12,t13,t17,t18,t24), nrow=9, ncol=10410, byrow=TRUE)

for(i in 1:9){for(j in 1:9){for(k in 1:9){for(l in 1:9){for(m in 1:9){for(n in 1:9){for(o in 1:9){
   for(p in 1:9){for(q in 1:9){assign(paste0("sum",i,j,k,l,m,n,o,p,q),sum(ifelse(uncommontests[i,]& 
     uncommontests[j,]& uncommontests[k,]&uncommontests[l,] & uncommontests[m,]& uncommontests[n,]&
     uncommontests[o,] & uncommontests[p,]& uncommontests[q,],1,0)/10410*100))}}}}}}}}}

I tried this to avoid for loops, but it doesn't loop through anything and I'm not sure how to expand this to do what I have above.

unc1=matrix(cbind(apply(uncommontests,1,function(x) {ifelse(uncommontests[1,],1,0)})),nrow=1,ncol=10410)

Aucun commentaire:

Enregistrer un commentaire