'R: loop over all variables and display a frequency table for each

I have a data frame and I need to display a frequency table for each variable. The following code does not work (no error message but no tables printed) and I can't find the solution despite extensive searching. I would be grateful for pointers.

varlist <- names(df)
for (var in varlist) {
   mytable <- table(paste("df$", var, sep = ""))
   mytable
}

I am not working on my machine so I would prefer to stick to base R if possible, to avoid installing packages.



Solution 1:[1]

As long as categorical variables are of factor data type, summary(df) will give you frequency tables for each of them.

Alternatively, you can use lapply to loop table over the columns: lapply(df[names(df)], table))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrea M