kquach
kquach

Reputation: 161

loop for tabulation of variables in data frame

I have a df with n variables. I want to loop through a subset of the variables and produce a frequency table.

For example, given df below:

id a b c d 
1 0 1 0 1 
2 1 0 1 0
3 0 1 0 1

I tried to do the following without success:

varlist <- c("a", "c")

for (i in varlist){
   print(table(df$i))
               }

Upvotes: 0

Views: 1918

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

(First, your matrix df is transformed to a data frame:)

df <- setNames(as.data.frame(df), letters[1:4])

The $ does not work with variables. You have to use [[ instead:

for (i in varlist){
  print(table(df[[i]]))
}

However, a much easier solution for your problem is lapply:

lapply(df[varlist], table)

From the help page of Extract:

The main difference is that $ does not allow computed indices, whereas [[ does.

Upvotes: 2

Related Questions