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

Count the values of a column based on the values of another column in R

Using the dataframe I want to create a new one which will contain Zip, Name and a column named Count which will include the count of Name per Zip.

Zip<-c("123245","12345","123245","123456","123456","12345")
Name<-c("Bob","Bob","Bob","Jack","Jack","Mary")
df<-data.frame(Zip,Name)

library(dplyr)
df %>%
  group_by(Zip) %>%
  mutate(Name = cumsum(Name))

expected

Zip Name Count
1 123245  Bob     2
2  12345  Bob     1
3  12345 Mary     1
4 123456 Jack     2

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 :

Does this solve your problem?

Zip<-c("123245","12345","123245","123456","123456","12345")
Name<-c("Bob","Bob","Bob","Jack","Jack","Mary")
df<-data.frame(Zip,Name)

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df %>%
  group_by(Zip, Name) %>%
  summarise(Count = n())
#> `summarise()` has grouped output by 'Zip'. You can override using the `.groups` argument.
#> # A tibble: 4 × 3
#> # Groups:   Zip [3]
#>   Zip    Name  Count
#>   <chr>  <chr> <int>
#> 1 123245 Bob       2
#> 2 12345  Bob       1
#> 3 12345  Mary      1
#> 4 123456 Jack      2

Created on 2021-12-22 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