Metronome123 wrote on 09/27/2011 07:24:50 AM: > > Startsituation: > > structure(c(1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, > 0, 1, 1), .Dim = 4:5, .Dimnames = structure(list(subject = c("s1", > "s2", "s3", "s4"), class = c("c1", "c2", "c3", "c4", "c5")), .Names = > c("subject", > "class")), class = c("xtabs", "table"), call = xtabs(formula = ~subject + > class, data = ia)) > > I want a count of subjects that match the same classes in subject_cnt and a > count of the number of classes in class_cnt The result of this example > should be: > > structure(list(subject_cnt = c(2L, 1L, 1L), class_cnt = c(3L, > 2L, 3L), c1 = c(1L, 1L, 0L), c2 = c(0L, 1L, 0L), c3 = c(1L, 0L, > 1L), c4 = c(0L, 0L, 1L), c5 = c(1L, 0L, 1L)), .Names = c("subject_cnt", > "class_cnt", "c1", "c2", "c3", "c4", "c5"), class = "data.frame", row.names > = c(NA, > -3L)) > > How can I achieve this in R, without complicated loops? > > PS. Note that the number of classes and subjects are in real quite big. > > Cheers, > > > Lars
Try this: xt <- structure(c(1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1), .Dim = 4:5, .Dimnames = structure(list(subject = c("s1", "s2", "s3", "s4"), class = c("c1", "c2", "c3", "c4", "c5")), .Names = c("subject", "class")), class = c("xtabs", "table")) df <- as.data.frame(unclass(xt)) dfu <- unique(df) class_cnt <- apply(dfu, 1, sum) subject_cnt <- tabulate(match(apply(df, 1, paste, collapse="-"), apply(dfu, 1, paste, collapse="-"))) data.frame(subject_cnt, class_cnt, dfu) Jean [[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.