0

I am trying to use the count() function from the dplyr package on every column of my data frame to count the number of each value per column in my df.

I tried :

apply(df, 2, function(x){count_(df,X[1])})       

However, it does not work. If I do

apply(df, 2, function(x){count_(df,"one of my column's name")})

it only applies it to that column.

How can I apply it to every column in my data frame ?

Buzz Lightyear
  • 824
  • 1
  • 7
  • 18
  • Welcome to Stack Overflow! Can you please include data and/or code that will provide us with a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) ? – Ben Bolker May 11 '16 at 17:14
  • 2
    `x` is not the same as `X`. And don't refer to df inside the function. That's what is causing you grief. The `x` is the column of interest. Just `count_` or `count` it. – IRTFM May 11 '16 at 17:15
  • 1
    `apply(df, 2, ...)` is very wrong for `data.frame`'s. Use `lapply`. – eddi May 11 '16 at 17:39

2 Answers2

1

How about the following:

apply(df, 2, table)
Abdou
  • 12,931
  • 4
  • 39
  • 42
russodl
  • 96
  • 2
0

Probably a lot of elegant ways to do this, but try this:

zz=apply( iris  , 2 , function(x) { table(x) })

zz will be a list of occurrence counts, one list item for each column. You could merge it all together if you want from there.

Edit: I just noticed someone above did the same with just "table" instead of the function definition. Both will work, I always use a function since I end up messing around with it a bit.

JoshK
  • 337
  • 4
  • 16