# Using n() at the same time as calculating other summary statistics

I am having trouble to prepare a summary table using `dplyr` based on the data set below:

``````set.seed(1)
df <- data.frame(rep(sample(c(2012,2016),10, replace = T)),
sample(c('Treat','Control'),10,replace = T),
runif(10,0,1),
runif(10,0,1),
runif(10,0,1))

colnames(df) <- c('Year','Group','V1','V2','V3')
``````

I want to calculate the mean, median, standard deviation and count the number of observations by each combination of `Year` and `Group`.

I have successfully used this code to get `mean`, `median` and `sd`:

``````summary.table = df %>%
group_by(Year, Group) %>%
summarise_all(funs(n(), sd, median, mean))
``````

However, I do not know how to introduce the `n()` function inside the `funs()` command. It gave me the counting for `V1`, `V2` and `V3`. This is quite redundant, since I only want the size of the sample. I have tried introducing

``````    mutate(N = n()) %>%
``````

before and after the `group_by()` line, but it did not give me what I wanted.

Any help?

EDIT: I had not made my doubt clear enough. The problem is that the code gives me columns that I do not need, since the number of observations for `V1` is sufficient for me.

• Can you add `()` after `n` to make the code workable? like this: `summarise_all(funs(n(),sd,median,mean))` – raymkchow Jul 11 '17 at 2:01
• Check stackoverflow.com/questions/22801153/… and see if it helps – Kevin Jul 11 '17 at 2:12
• @raymkchow I have edited the question. Now it is clear. – Arthur Carvalho Brito Jul 11 '17 at 2:15
• Since you are counting numbers of each group in group_by, you don't care if the number of observations are of V1, V2 or V3. I would do like this: `... %>% summarise_all(funs(sd,median,mean)) %>% mutate(n = n()) ` – raymkchow Jul 11 '17 at 2:18
• It does not work, n always comes as n = 2, which is not true – Arthur Carvalho Brito Jul 11 '17 at 2:31

Add the `N` column before summarizing as an extra grouping column:

``````library(dplyr)
set.seed(1)

df <- data.frame(Year = rep(sample(c(2012, 2016), 10, replace = TRUE)),
Group = sample(c('Treat', 'Control'), 10, replace = TRUE),
V1 = runif(10, 0, 1),
V2 = runif(10, 0, 1),
V3 = runif(10, 0, 1))

df2 <- df %>%
group_by(Year, Group) %>%
group_by(N = n(), add = TRUE) %>%
summarise_all(funs(sd, median, mean))

df2
#> # A tibble: 4 x 12
#> # Groups:   Year, Group [?]
#>    Year   Group     N      V1_sd      V2_sd     V3_sd V1_median V2_median
#>   <dbl>  <fctr> <int>      <dbl>      <dbl>     <dbl>     <dbl>     <dbl>
#> 1  2012 Control     2 0.05170954 0.29422635 0.1152669 0.3037848 0.6193239
#> 2  2012   Treat     2 0.51092899 0.08307494 0.1229560 0.5734239 0.5408230
#> 3  2016 Control     3 0.32043716 0.34402222 0.3822026 0.3823880 0.4935413
#> 4  2016   Treat     3 0.37759667 0.29566739 0.1233162 0.3861141 0.6684667
#> # ... with 4 more variables: V3_median <dbl>, V1_mean <dbl>,
#> #   V2_mean <dbl>, V3_mean <dbl>
``````

Are you getting the same error I am:

“Error in n(): function should not be called directly”

If so, there's a stack question on that here that might help: dplyr: "Error in n(): function should not be called directly"

The resolution seems to be detaching `plyr` where there appears to be a conflict and reloading the `dplyr` library.
{"ft_lang_label":"__label__en","ft_lang_prob":0.82180524,"math_prob":0.9164951,"size":1300,"snap":"2019-51-2020-05","text_gpt3_token_len":387,"char_repetition_ratio":0.090277776,"word_repetition_ratio":0.019512195,"special_character_ratio":0.32076922,"punctuation_ratio":0.19727892,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9882003,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-15T07:53:40Z\",\"WARC-Record-ID\":\"<urn:uuid:512216e5-c0ba-48cd-aba4-ea908f8071fc>\",\"Content-Length\":\"148755\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e2a20e94-330d-4164-a62b-e1aa792fe49a>\",\"WARC-Concurrent-To\":\"<urn:uuid:558a7756-04dd-483e-aecf-3ca3b767f97d>\",\"WARC-IP-Address\":\"151.101.65.69\",\"WARC-Target-URI\":\"https://stackoverflow.com/questions/45024158/using-n-at-the-same-time-as-calculating-other-summary-statistics\",\"WARC-Payload-Digest\":\"sha1:UNNH2TDJIEMVE24SHIQS5S3PWJKL4PFW\",\"WARC-Block-Digest\":\"sha1:QLMIFAYRX2DYMD5D3SSLIULFAJMCBSUU\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575541307797.77_warc_CC-MAIN-20191215070636-20191215094636-00269.warc.gz\"}"}