Yan
Yan

Reputation: 1

loop over variable names in R and do a tabulation of the variable within the loop

I have a data set with some categorical variables, say "x", "y", "z". I want to do a loop and tabulate each of the variables of the data set. Let's say the name of the data set is "df". I know a package named "tidyverse" and I can use the following codes to get the stats I need after loading this package:

df %>% count(x)
df %>% count(y)
df %>% count(z)

But instead of typing these similar codes 3 times, I want to do it via loop. I tried to do it like this,

varnames <- c("x", "y", "z")

for (i in 1:length(varnames)) {
  df %>% count(varnames[i])
}

But it didn't show me anything. I was expecting same returns as typing the codes 3 times respectively. Does anyone know what's wrong with the loop above or how to do this, i.e. loop over a list of variable names and refer the variable within the loop and generate some stats.

Many thanks!

Upvotes: 0

Views: 108

Answers (1)

Gangesh Dubey
Gangesh Dubey

Reputation: 382

following should do the trick

lapply(df,table)

Upvotes: 1

Related Questions