Ken
Ken

Reputation: 101

Trying to create a function that ensures the length of the list is 2

I am trying to create a function that will check if the length of my list is 2, and if so, it goes on to the next step. I haven't written the next steps, as I can't get the first step to accurately check. Here is what I have come up with so far:

  my_function <- function(x) {
  if(length(x) <- 2) {
    return("Correct Length") 
  } 
}

When I run this function with:

my_function(list(c(3)))
my_function(list(c("text")))
my_function(list(c(6, 7), c(2, 4)))

I get the following results:

[1] "Correct Length"
[1] "Correct Length"
[1] "Correct Length"

I am sure this is how I am measuring my length, but if I try to add 'list' to the code. I am not sure why my function is evaluating the first two items as TRUE, as only the their input should evaluate to TRUE.

Any suggestions would be help as I continue to learn.

Upvotes: 3

Views: 37

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70623

<- is used for assigning values to variables, == is used for checking equality. Your check should thus be

if (length(x) == 2) {
    ...
}

Upvotes: 4

Related Questions