2
\$\begingroup\$

I am new to programming / R and new to writing functions. I am working through the book R for Data Science and am on the following exercise:

Implement your own version of every() using a for loop.

In case you're unaware, the every function from purrr does the following:

Do every element of a list satisfy a predicate?

Here is the function I came up with:

every_2 <- function(x, fun) {
  output <- vector("logical", length(x))
  output2 <- vector("logical", length = 1L)
  for (i in seq_along(x)) {
    output[[i]] <- fun(x[[i]])
    if (sum(output) < length(output)){
      output2 <- FALSE
    } else {
      output2 <- TRUE
    }
  }
  output2
}

Using the following numeric vector:

test_vec <- 1:100

The output matches that of the original every function.

every(test_vec, function(x) {x > 0}) # TRUE
every(test_vec, function(x) {x > 100}) # FALSE
every(test_vec, is.character) # FALSE
every(test_vec, is.numeric) # TRUE

every_2(test_vec, function (x) {x > 0}) # TRUE
every_2(test_vec, function(x) {x > 100}) # FALSE
every_2(test_vec, is.character) # FALSE
every_2(test_vec, is.numeric) # TRUE

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.