Home > Net >  Looking for an R function that counts number of times two columns appear together
Looking for an R function that counts number of times two columns appear together

Time:07-23

I have a data.frame with many rows. I am trying to produce a new data.frame summarizing the total row count for all combinations of V_ID and N_ID.

In the below, df1 is an example of my data and df2 is an example of the desired output.

df1 <- data.frame (V_ID  = c(1234, 5252, 1234, 1234, 1234, 5252, 5252, 6754),
                  N_ID = c(45, 23, 45, 45, 45, 22, 23, 11),
                  Length = c(88, 33, 88, 88, 88, 33, 33, 22)
                  )

df2 <- data.frame (V_ID  = c(1234, 5252, 5252, 6754),
                  N_ID = c(45, 23, 22, 11),
                  Num_Times=c(4, 2, 1, 1),
                  Length = c(88, 33, 33, 22)
                  )

Is there a way to do this in dplyr?

CodePudding user response:

You can use count() from the dplyr package.

library(dplyr)

df1 %>% count(V_ID, N_ID, Length, name = "Num_Times")
#>   V_ID N_ID Length Num_Times
#> 1 1234   45     88         4
#> 2 5252   22     33         1
#> 3 5252   23     33         2
#> 4 6754   11     22         1
  • Related