That can be an advantage. Every R problem can be thought of with advantage as the interaction of three objects— an existing object, x , a desired object,y , and a function, f, that will return a value of y given x as an argument. In other words, school algebra— f(x) = y. Any of the objects can be composites.
In this problem the information at hand consists of integers in two pieces: j is a single integer and n is a sequence of integers; taken together they are the x of the equation. y is the length of a vector of the integers in n that satisfy the condition that the last digit is the same as j.
Everything in R is an object; objects have properties depending on the class; some are containers for data and others perform functions. Functions are said to be first-class objects—that just means that they can be given as arguments to other functions, just like f(g(x) = y.
Let's tackle the simplest parts of the problem, first.
Our goal is a function f that will take j and n and do something. It will look like
the_function <- function(x,y) # do something next
Call it with j and n is just
the_function(2,1:10)
for example. The 2 represents the integer we want to match and 1:10 is the sequence of integers from one to 10. : expands to `c(1,2,3,4,5,6,7,8,9,10).
Assume we have a vector as a result of the_function, and we want to know: How many?
length(my_vector)
That's simple enough.
For the rest of the work, we're going to call on the {stringr} package, which is good to deal with patterns in strings. Why strings and not integers? Because it's much easier to convert the numbers to characters and do a simple search.
For that we first need another simple, builtin— as.character, which converts an integer to a character.
Then we need to describe how to recognize a last character in a string.
last_one <- ".$"
which translates to . = a single character and $ the end of the string.
So, now we are in a position to identify the final characters (string representations of the integers, "1", etc. The final piece is which, which allows us to gather up all of the last integers that match the target.
suppressPackageStartupMessages({
library(stringr)
})
target <- ".$"
get_last <- function(j,n) which(str_extract(as.character(n),target) == as.character(j))
get_last(2,1:100)
#> [1] 2 12 22 32 42 52 62 72 82 92
length(get_last(2,1:100))
#> [1] 10