0

This problem is driving me crazy and I can't figure it out. Here is a subset of my dataframe (df) to make things easier.

enter image description here

I want to group_by sex and count the total. Simple?

df %>% group_by(sex) %>% count()

This code returns the following output

enter image description here

What I wanted (and what I thought this code did when I used it before (maybe my memory is bad) was this output

enter image description here

I obtained this output using

df %>% group_by(sex) %>% tally()

I have nothing against tally() but I swear I was using count() before.

Also, I thought I could use group_by %>% summarize(n()) to get the same result, but when I try this code

df %>% group_by(sex) %>% summarize(n())

I get this message

enter image description here

Again, I 'thought' this would work and produce similar output, but it's not. Maybe I'm misremembering things and the least you can do is tell me to get my memory checked :-D

Thanks in advance

p.habermanm
  • 85
  • 1
  • 9
  • Try using `df %>% group_by(sex) %>% dplyr::count()` you might have `plyr` loaded in your session. – Ronak Shah Oct 29 '20 at 06:15
  • Also please don't add data as images, share them in a reproducible format using which we can test the solution. We cannot copy data from an image. – Ronak Shah Oct 29 '20 at 06:21
  • @RonakShah Strangely, when I copy and past the code you give, it works fine. I already had dplyr loaded. I loaded it again just in case. Same result as my earlier problem. – p.habermanm Oct 29 '20 at 06:21
  • you also have `plyr` loaded which masks functions `summarise` and `count`. Restart R and load only `dplyr`. – Ronak Shah Oct 29 '20 at 06:24
  • I restarted R and tried it. It worked. Thank you. I had plyr and dplyr both loaded for that session. That must be why. So, having both libraries loaded in the same session can cause certain issues like this? – p.habermanm Oct 29 '20 at 06:57

1 Answers1

0

if you want output like this

enter image description here

add column name before your n() function. here's the example

df %>% group_by(sex) %>% summarize(num_of_sex = n())
jolii
  • 97
  • 8
  • The solution was found, thanks. It was due to having plyr and dplyr both loaded in the session. The code you provided works now. – p.habermanm Oct 29 '20 at 06:59