How to count number of unique character vectors wi

2019-07-19 18:39发布

问题:

Here is an example of my dataset:

Dput -

(removed)

And I am subsetting this data frame by month using this code:

simpleindoor.mean <- simple_trapindoors %>% group_by(month) %>% summarise(n=n(),mean = mean(bitingrate), stderror = std(bitingrate))

Which produces a table like the following:

  |Month| n |   mean| stderror|
  |-----|---|-------|---------|                          
  |May  | 12|   0.25|     0.13|
  |June | 21|   0.53|     0.12|
  |July | 21|   0.53|     0.12|

What I would like to do is calculate the number of individual FAMILY_ID's within each month in the same function, and add it as a new column to "simpleindoor.mean".

FAMILY_ID is a character vector. E.g."6001-032". So if there were 12 unique FAMILY_ID's in May, the new column of data would show 12 in the row matching "May".

I have seen examples where you look for specific instances of a character vector, but I struggled to find an example where you can count the instances of unique character vectors occurring within a particular group. How do I do this?

Thank you.

回答1:

You need n_distinct

simple_trapindoors %>% group_by(month) %>% summarise(n=n(),mean = mean(bitingrate), stderror = std(bitingrate), 
                                                     UniqueFamilies = n_distinct(FAMILY_ID))


标签: r vector dplyr