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

Creating vector based on whether dataframe values are divisible by ten

library(babynames)

I am looking to make a vector of all decade marker years AKA years in the babynames package that are divisible by 10.

range(babynames$year)

told me the years in the set are 1880-2017 and I made the following solution

c(seq(from=1880,to=2017,10))

However if the range of babynames did not begin on a number that ended with 10 this example would not work. So now I am looking to find a solution that finds all the decade markers (1890,1900,1910…) between numbers if the first is for ex. 1881

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

I expect this is possible by checking whether the year between 1881-2017 is divisible by 10 resulting in an integer, and if it is, listing it. How do I do this?

Something like this pseudo code

for (i in 1881:2017) {
  if (is.integer(i/10)==TRUE)
  c(i)

>Solution :

Using the modulo operator %% which gives the remainder of a division you could do:

library(babynames)

years <- sort(unique(babynames$year))
years[years %% 10 == 0]
#>  [1] 1880 1890 1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 2010
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