LegendOfKass
LegendOfKass

Reputation: 191

What to do when the "which" function doesn't find the value?

error message I get this error when the which function cannot find the value. I want it to simply return a value indicating that nothing was found. How would I do that? Also I'd like to use a for loop to reiterate through each variable in the dataframe, how would I look at each column in the dataframe individually? I just need to know how to call up the columns or rows of the matrix, I'm good with loops -- Ive been programming for years, just a little new to r. Thank you!

Day1 = c("S", "Be", "N", "S", "St")
Day2 = c("S", "S", "M", "Ta", "Sa")
Day3 = c("S", "Ba", "E", "Te", "U")
Day4 = c("V")

Week = data.frame(Day1, Day2, Day3, Day4)
print(Week)

n = which(Week$Day4 == "S")

if (n[1] == 1) {
  print("true")
} else {
  print("false")
}

Upvotes: 0

Views: 739

Answers (1)

Dioney Blanco
Dioney Blanco

Reputation: 56

The output of the which() function is a vector, so if no value is found for the which()function is integer(0) so I recommend instead of having in your ifstatement n[1] == 1 change it to if( length(n) > 0 ) that means there's a match in the given column.

To your second question, a simple way is to use index of the data.frames to iterate through the columns

n_columns <- ncol(Week) 

# this will iterate through all the columns.
for( i in 1:n_columns ){
 idx <- which(Week[ , i] == "S")
}

Obviously this will update the idx value in each for iteration, so you would like to save True, False output in a vector if you're saving the 'true'/'false' prints.

In the code the brackets mean Week[ rows , columns] if there is no input like in my example Week[ , i ] it means you want to get all rows for column i.

Hope this helps!

Upvotes: 1

Related Questions