AHF
AHF

Reputation: 1072

If condition is not showing the result

I am running below code, its working but not showing me output

for (name in tita$name){
  if (tita$sex == 'female' && tita$embarked == 'S' && tita$age > 33.00)
  {
    print (name)
  }
}

It's just showing me ****** in R studio, though when I check dataset, it has data which have female having age greater than 33 and embarked from S, but this statement is not showing me result. But when I change the value from 33 to 28 the same code shows me the result. Why is that.

I am using the following dataset:

https://biostat.app.vumc.org/wiki/pub/Main/DataSets/titanic3.csv

Upvotes: 0

Views: 50

Answers (1)

LMc
LMc

Reputation: 18672

I think you're mixing loops and vectorization where you shouldn't. As I mentioned in the comments your conditions are vectorized, but it looks like you're trying to evaluate each element in a loop.

You should do either:

# loop through elements
for (i in seq_along(tita$name)){
  if (tita$sex[i] == 'female' & tita$embarked[i] == 'S' & tita$age[i] > 33.00){
    print(tita$name[i])
  }
}

OR use vectorization (this will be faster and is recommended):

conditions <- tita$sex == 'female' & tita$embarked == 'S' & tita$age > 33.00
names <- tita$name[conditions]

Here conditions is a TRUE and FALSE logical vector -- TRUE where all the conditions are met. We can use the to subset in R. For more information on what I mean by vectorization please see this link.

Upvotes: 1

Related Questions