-2

Am kindly looking for R code that can calculate the combinations with 2, of the total in each group.

library(dplyr)
    id<-c(1,1,1,1,2,2,2,2,3,3,3,3)
    sex<-c(1,1,1,1,1,1,1,1,1,1,1,1)
    ds<-data.frame(id,sex)
    out1<-ds %>% group_by(id) %>% summarise(n=n())
    

My output should be

 id<-c(1,2,3)
    n<-c(4,4,4)
    ncomb2<-c(6,6,6)
    

Thankyou

Sam Mwenda
  • 150
  • 8
  • 1
    I don't understand the logic behind your task. Could you explain it in more detail? – Martin Gal Jul 22 '20 at 09:29
  • 1
    Please reword the question, as "calculate the combinations of that total in each group" is unclear – Robert Wilson Jul 22 '20 at 09:30
  • Dear robert, i have edited – Sam Mwenda Jul 22 '20 at 09:35
  • Dear martin, the task is to count the total in each group by ID, which i have done, i now want a combination with 2 of each total – Sam Mwenda Jul 22 '20 at 09:37
  • can you explain the logic why n_comb_id1_and_2 = 6? – maarvd Jul 22 '20 at 09:40
  • Edited my code to include a simple output considering I have grouped by id(1,2,3), then did a count of the ids(4,4,4) then did a combination of the counts by 2 (6,6,6). Therefore, my request is a single code to do this. Regards – Sam Mwenda Jul 22 '20 at 09:47
  • I'm not sure if your revision makes sense. Your question is about group_by which is a dataframe operation, but you want vectors as output? Unless your problem is clearly stated you are not likely to get a correct solution – Robert Wilson Jul 22 '20 at 10:29

1 Answers1

1

I am not sure if the code below is what you are after

out1 <- ds %>%
    group_by(id) %>%
    summarise(n = n()) %>%
    mutate(ncomb2 = choose(n,2))

such that

> out1
# A tibble: 3 x 3
     id     n ncomb2
  <dbl> <int>  <dbl>
1     1     4      6
2     2     4      6
3     3     4      6
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81