Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading