1

I'm just trying to run a for loop that identifies which row numbers register as TRUE and prints it in the console.

 Holidays <- c("TRUE", "TRUE", "FALSE", "TRUE")


 newvector <- for (i in 1:length(Holidays))
         {
             if (i == TRUE)
               print(i)
    } 
tadman
  • 208,517
  • 23
  • 234
  • 262
hmnoidk
  • 545
  • 6
  • 20

4 Answers4

4

If you want to store which rows are TRUE preallocate an empty vector and bind it in the loop.

If you really have TRUE and FALSE as strings, do the following

Holidays <- c("TRUE", "TRUE", "FALSE", "TRUE")
store = c()

for (i in 1:length(Holidays)){
             if (Holidays[i] == "TRUE") # here you want to see whether the element inside Holiday is equals "TRUE"
              store = c(store, i) # store vector you give you which rows are "TRUE"
    } 

However, if you have actual logical entries in Holidays, then the correct syntax should be

Holidays <- c(TRUE, TRUE, FALSE, TRUE)
store = c()

for (i in 1:length(Holidays)){
             if (Holidays[i] == TRUE)
              store = c(store, i)
    } 

However, as @Badger mentioned, there is no need to loop here. You can easily get the indices using which

store = which(Holidays %in% TRUE)
Felipe Alvarenga
  • 2,572
  • 1
  • 17
  • 36
2

So using this question as a guide, the command below will get a vector of index numbers from the Holidays vector that match "TRUE":

true_indexes = which(Holidays %in% "TRUE")
print(true_indexes)
Tom Cooper
  • 611
  • 1
  • 8
  • 16
1

EDIT Please disregard my answer, it is not correct, as it had been pointed out to me.

===========================================================================

Your problem is that you store TRUE and FALSE as strings, not as booleans.

Instead of

Holidays <- c("TRUE", "TRUE", "FALSE", "TRUE")

You should have:

Holidays <- c(TRUE, TRUE, FALSE, TRUE)

The rest of your code should work.

kgolyaev
  • 565
  • 2
  • 10
1

Why do you want to do it with a for loop ? If you change cour mind you can do it with which. Works with non boolean, too

newvector <-which(Holidays == "TRUE")
  • Thanks. I am a newbie and I was just very stubborn about pulling off a for loop, haha. For my own amusement. – hmnoidk Mar 08 '18 at 21:53