Hi, I have a matrix with few hundred by a few hundred and want to extract rows, e.g. (0,1,0), or (1.3, 2.4, 4). I made an example:> A = rep(rep(c(0,1),4),2) > B = rep(rep(c(0,1),each=4),2) > C = rep(rep(rep(c(0,1),2),each=2),2) > X = data.frame(A,B,C,rnorm(16))A B C [1,] 0 0 0 0.72767870 [2,] 1 0 0 -0.09673298 [3,] 0 0 1 0.51192790 [4,] 1 0 1 -1.54350441 [5,] 0 1 0 0.91775344 In this example, is there a better way of doing 'X[ X$A==1 & X$B == 0 & X$C ==1, 4]' ? I want to find the unique group definition by 'unique' and then extract rows corresponding each unique vector that is returned by 'unique' function. Thanks a lot Young. [[alternative HTML version deleted]]
Hi,>>A = rep(rep(c(0,1),4),2) >>B = rep(rep(c(0,1),each=4),2) >>C = rep(rep(rep(c(0,1),2),each=2),2) >>X = data.frame(A,B,C,rnorm(16)) >> >>> X = data.frame(A,B,C,D=rnorm(16)) > X A B C D 1 0 0 0 0.829987 2 1 0 0 1.319203 3 0 0 1 0.223752 4 1 0 1 0.017353 5 0 1 0 1.288284 6 1 1 0 1.384687 7 0 1 1 0.186565 8 1 1 1 -0.002799 9 0 0 0 -0.875205 10 1 0 0 1.872563 11 0 0 1 -0.317170 12 1 0 1 -0.766612 13 0 1 0 -1.423495 14 1 1 0 -0.042385 15 0 1 1 -1.191448 16 1 1 1 0.731018 > Q<-unique(X[1:3]) > Q A B C 1 0 0 0 2 1 0 0 3 0 0 1 4 1 0 1 5 0 1 0 6 1 1 0 7 0 1 1 8 1 1 1 > for(i in 1:nrow(Q)){ + print(X[apply(X[,1:3],1,function(x){all(x==Q[i,])}),]) + } A B C D 1 0 0 0 0.8300 9 0 0 0 -0.8752 A B C D 2 1 0 0 1.319 10 1 0 0 1.873 A B C D 3 0 0 1 0.2238 11 0 0 1 -0.3172 A B C D 4 1 0 1 0.01735 12 1 0 1 -0.76661 A B C D 5 0 1 0 1.288 13 0 1 0 -1.423 A B C D 6 1 1 0 1.38469 14 1 1 0 -0.04238 A B C D 7 0 1 1 0.1866 15 0 1 1 -1.1914 A B C D 8 1 1 1 -0.002799 16 1 1 1 0.731018 > HTH -- Ferdinand Alimadhi Programmer / Analyst Harvard University The Institute for Quantitative Social Science (617) 496-0187 falimadhi@iq.harvard.edu www.iq.harvard.edu [[alternative HTML version deleted]]