0
votes

I have a dataset (data.frame) named 'test', and there are 52 columns(predictors) named T1, T2, T3, T4, T5, T6,.......T50.

I want to extract the frequency table of each column.

I know there is a function for it named 'freq'.

Then, how can I get 50 frequency tables without manual 52 times coding.

Comment on it if you have any idea. Thank you.

1

1 Answers

2
votes

We can loop over the columns with lapply and apply table to get the frequency count of each column

lapply(test, table)

We could also convert the columns to factor with levels specified as the unique elements in the dataset, and then apply the table so that the list elements can be rbind to create a data.frame or matrix (to keep the length of list element to be the same by not dropping the unused levels)

Un1 <- sort(unique(unlist(test)))
do.call(rbind, lapply(test, function(x) table(factor(x, levels=Un1))))

Or another option is mtabulate

library(qdapTools)
mtabulate(test)

data

set.seed(24)
test <- as.data.frame(matrix(sample(1:8, 8*50, replace=TRUE),
   ncol=50, dimnames=list(NULL, paste0("T", 1:50))) )