Here is a possibility. There is only one trick. > data Q1_1 Q1_2 Q1_3 Q1_4 Q1_5 Q1_6 Q1_7 Q1_8 1 5 5 5 4 5 4 5 4 2 4 5 3 5 5 5 3 5 3 4 4 3 4 4 4 4 2 4 5 5 5 5 5 4 4 4 5 5 5 5 5 5 5 5 5 6 3 4 4 3 3 3 4 0 7 4 3 4 4 0 4 5 0 8 2 2 3 1 2 1 1 1 > vals <- sort(unique(as.vector(as.matrix(data)))) ### small trick! > vals [1] 0 1 2 3 4 5 > atad <- apply(data, 2, function(x) table(factor(x, levels = vals))) > atad ### almost there Q1_1 Q1_2 Q1_3 Q1_4 Q1_5 Q1_6 Q1_7 Q1_8 0 0 0 0 0 1 0 0 2 1 0 0 0 1 0 1 1 1 2 1 1 0 0 1 0 0 1 3 1 1 3 1 1 1 1 0 4 3 2 2 3 1 4 3 2 5 3 4 3 3 4 2 3 2 > atad <- t(atad) ### not sure why you want this! > atad 0 1 2 3 4 5 Q1_1 0 0 1 1 3 3 Q1_2 0 0 1 1 2 4 Q1_3 0 0 0 3 2 3 Q1_4 0 1 0 1 3 3 Q1_5 1 0 1 1 1 4 Q1_6 0 1 0 1 4 2 Q1_7 0 1 0 1 3 3 Q1_8 2 1 1 0 2 2 >
You need to be careful, though. You started with a data frame, and this is a matrix: > class(atad) [1] "matrix" You can turn it into a data frame, but... > data.frame(atad) X0 X1 X2 X3 X4 X5 Q1_1 0 0 1 1 3 3 Q1_2 0 0 1 1 2 4 Q1_3 0 0 0 3 2 3 Q1_4 0 1 0 1 3 3 Q1_5 1 0 1 1 1 4 Q1_6 0 1 0 1 4 2 Q1_7 0 1 0 1 3 3 Q1_8 2 1 1 0 2 2 > the column names will be transformed to syntactially valid names. Just be aware of this. Bill Venables. Bill Venables http://www.cmis.csiro.au/bill.venables/ -----Original Message----- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of arademaker Sent: Sunday, 29 March 2009 8:40 AM To: r-help@r-project.org Subject: [R] list of variables to table of factors Sorry about the simple question. Is there any function to transform a data.frame like this (rows are observations and columns are variables): Q1_1 Q1_2 Q1_3 Q1_4 Q1_5 Q1_6 Q1_7 Q1_8 1 5 5 5 4 5 4 5 4 2 4 5 3 5 5 5 3 5 3 4 4 3 4 4 4 4 2 4 5 5 5 5 5 4 4 4 5 5 5 5 5 5 5 5 5 6 3 4 4 3 3 3 4 0 7 4 3 4 4 0 4 5 0 8 2 2 3 1 2 1 1 1 Into a data.frame where the rows are the columns of the previous one and each column is a possible value for that variable. The data are the counting of observations for each variable vs possible value: 1 2 3 4 5 Q1_1 0 1 1 3 3 Q1_2 0 1 1 2 4 ... I know that I can use: tapply(x[["Q1_1"]],factor(x[["Q1_1"]], levels=1:5), length) to compute each row and than create a matrix of it. But I wonder if there is some function already defined for doing this transformation. Cheers, Alexandre ______________________________________________ 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.