0
votes

Suppose I have a data frame with several categorical features. How do I compute freq distribution table using for loop instead of finding individual distributions

I used the following code:

data
         a   b  c  
1  class 1   1  M 
2  class 2   0  F 
3  class 3   0  M 
4  class 1   1  F    
5  class 1   1  F
6  class 2   1  M    
7  class 1   0  F   
8  class 1   0  F 
9  class 2   1  M    
10 class 2   1  M 
11 class 3   1  F    
12 class 3   0  F    

>b<-data$b
>b.freq<-table(b)
>b.freq

0  1
5  7

I want to do this for all the variables in a larger set with for loop.

Please help

thanks

1

1 Answers

2
votes

If you want to apply the table function to all columns, you can use lapply:

> lapply(data, table)
$a

class 1 class 2 class 3 
      5       4       3 

$b

0 1 
5 7 

$c

F M 
7 5 

Update: How to create the plots:

par(mfrow = c(1, length(data))); 
lapply(data, function(x) barplot(table(x)))

enter image description here