I am doing this practice problem that wants me to write a function that can calculate the digits that occur the most number of times in the array.
The example is input x= c(25, 2, 3, 57, 38, 41)
, and the return value is 2, 3, 5, since these numbers 2, 3 and 5 all occurs 2 times which is the most.
I am new to programming and I have no clue that how I can approach this.
CodePudding user response:
One approach would look something like this, although I am sure there are more efficient approaches:
my_vector <- c(25, 2, 3, 57, 38, 41)
# function to evaluate the number of times a certain digit occurrs
digit_occurrence <- function(vector) {
# collape vector to a single string without commas
x <- paste(vector, sep = '', collapse = '')
# create empty vector
digit <- c()
# loop over each unique digit and store its occurrence
for(i in paste(as.character(0:9))) {
digit[i] <- lengths(regmatches(x, gregexpr(i, x)))
}
digit
}
> digit_occurrence(my_vector)
0 1 2 3 4 5 6 7 8 9
0 1 2 2 1 2 0 1 1 0
CodePudding user response:
This could be another option for you:
fn <- function(x) {
# First We separate every single digit in each element but we need to turn
# the each element into character string beforehand. We then use do.call
# function to apply c function on every element of the resulting list to
# flatten the list to a vector
digits <- do.call(c, sapply(x, function(y) strsplit(as.character(y), "")))
# Then we turn the resulting character vector into numeric
digits_num <- as.numeric(digits)
# In the end we calculate the frequencies and sort the in decreasing order
most_freq <- sort(table(digits_num), decreasing = TRUE)
most_freq
}
fn(x)
digits_num
2 3 5 1 4 7 8
2 2 2 1 1 1 1