Home > Software engineering >  R: loop over all variables and display a frequency table for each
R: loop over all variables and display a frequency table for each

Time:03-22

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.

CodePudding user response:

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))

  • Related