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

R create column in new data frame if cells values match in two columns

I have a data frame ‘DF1’ with two columns that might have repeat data like such:

Date Name
2022-03-13 Bob
2022-03-13 Bob
2022-03-13 Tim
2022-03-14 Bob
2022-03-13 Tim
2022-03-14 Jim

I want to create a new data frame ‘DF2’ that populates a new column called ‘Count’ that counts those repeats with the prefix ‘Count’. The new data frame should also include the Date and Name information from the original column so that the new data frame looks like this:

Date Name Count
2022-03-13 Bob Count 2
2022-03-13 Tim Count 2
2022-03-14 Bob Count 1
2022-03-14 Jim Count 1

Thank you for your help!

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 :

To get the prefix "Count" you can use the paste() function, e.g.

library(dplyr)

df <- read.table(text = "Date   Name
2022-03-13  Bob
2022-03-13  Bob
2022-03-13  Tim
2022-03-14  Bob
2022-03-13  Tim
2022-03-14  Jim", header = TRUE)

df %>%
  group_by(Name, Date) %>%
  summarise(Count = paste("Count", n(), sep = " ")) %>%
  arrange(desc(Count))
#> `summarise()` has grouped output by 'Name'. You can override using the
#> `.groups` argument.
#> # A tibble: 4 × 3
#> # Groups:   Name [3]
#>   Name  Date       Count  
#>   <chr> <chr>      <chr>  
#> 1 Bob   2022-03-13 Count 2
#> 2 Tim   2022-03-13 Count 2
#> 3 Bob   2022-03-14 Count 1
#> 4 Jim   2022-03-14 Count 1

Created on 2022-08-15 by the reprex package (v2.0.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