> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of Ashta > Sent: Tuesday, October 13, 2009 5:20 AM > To: R help > Subject: [R] Counting > > *Hi all, > * > > *Assume that I have the following data set with tow > variables and I want > count the number of observation with identical values > * > > ** > > *x1 x2* > > * 1 1 * > > * 1 0 * > > * 0 1* > > * 0 1* > > * 0 0* > > * 1 1* > > * 0 1 > * > > > I want the following output > ** > > * > * > > *n1=3 # number of identical observation between x1 and x2 variables* > > *n2=4 # number of different observation*
sum() converts TRUE to 1 and FALSE to 0 so the following works n1 <- sum(x1 == x2) n2 <- sum(x1 != x2) You can also use table() to get both numbers in one vector. In the following I make table's input a factor (a) to make sure that both the == and != counts are in the table even if one count is zero and (b) to put them in the order you asked for, TRUE then FALSE: n12 <- table(factor(x1==x2, levels=c(TRUE,FALSE))) n1 <- n12[1] n2 <- n12[2] If there may be missing values in the data then you have to decide how to handle them. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > > > How do I do it in R? > > > Thanks a lot > > > > > ** > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.