datadude_ad
datadude_ad

Reputation: 23

Can't seem to get function to work, integer(0)

I am trying to count or sum the number of 1s and 0s in a function I created. But for some reason it keeps returning a class of (null) or an integer(0). What am I doing wrong and can someone please explain?

set.seed(4233) # set the random seed for reproducibility
vec1 <- sample(x = 0:9, size = 15, replace = TRUE)
vec1
test1 <- function(n){
  for (i in n)
    if (i %% 2 == 0){
      print(1)
    } else {
      print(0)
    }
}
testing <- test1(vec1)
length(which(testing == 1))

Upvotes: 1

Views: 40

Answers (1)

akrun
akrun

Reputation: 887691

Here, the issue is that the function returns nothing. It is just printing value. Instead, we can store the output in a vector

test1 <- function(n){
  v1 <- numeric(length(n)) # initialize a vector of 0s to store the output
  for (i in seq_along(n)) { # loop through the sequence of vector
   if (n[i] %% 2 == 0){
     v1[i] <- 1   # replace each element of v1 based on the condition

   } else {
     v1[i] <- 0
     }

    }
   v1  # return the vector
 }

test1(vec1)
#[1] 1 0 0 0 0 0 0 0 0 0 0 1 1 0 1

Note that this doesn't require any for loop

as.integer(!vec1 %%2)
#[1] 1 0 0 0 0 0 0 0 0 0 0 1 1 0 1

Upvotes: 1

Related Questions