[R] if then statement problem
Salas, Andria Kay
aks2515 at uncw.edu
Thu Nov 27 19:02:20 CET 2008
I really need help with an if then statement I am having trouble with. A brief explanation of what I am trying to do: I have a p matrix of all permutations of a vector of length 3 filled with either 1s or -1s (these make up the columns). The p.unique matrix is the unique columns of the p matrix; here, they are identical but in my real script this will not always be the case. I want to be able to take a randomly generated vector and see which column in the p.unique matrix, if any, match the random vector. If there is a match, I get an integer returned that tells me which column is the match. If there is no match, I get the response integer (0). I want to write an if then statement that allows me to do different things based upon if there is a match to one of the columns in the p.unique matrix or not. Below is a sample script plucked from bits of my "master script" that show this problem. The vector "r" was made to not match any columns in p.unique. If it did, "c" would equal the integer representing the matching column, and since it does not, I want c to equal the vector (0,0,0). My if then statement is not working (I keep getting the error that my argument is of length zero), so I would really appreciate any help anyone can provide me. Thanks for all of your help previously and in advance for the help with this problem!! Happy Thanksgiving!
p=as.matrix(do.call(expand.grid,rep(list(c(-1,1)),3)))
p=t(p)
p.unique=unique(p,MARGIN=2)
r=c(2,2,2)
q=which(apply(p.unique,2,function(x)all(x==r)))
if(q>0){c=p.unique[,q]};{c=c(0,0,0)}
More information about the R-help
mailing list