Error Na/ NaN argument

Hello.
Have to solve this question for my assignment and can't get a result:
Use the for loop and if control statements to list the men’s names whose ages are above 50 that embarked from C (Cherbourg) on the Titanic
I used the following code:
for (i in 1:(titanicDataset)){
if(!is.na(titanicDataset$age[i]) && titanicDataset$age>50 && titanicDataset$sex[i]=="male" && titanicDataset$embarked[i]=="C"){men_names<-c(men_names, TitanicDataset$name[i])}
else{next}
men_names<-na.omit(men_names)
}
men_names
length(men_names)

It keeps showing Error in 1:(titanicDataset) : NA/ NaN argument
In addition: warning message:
In 1: (titanicDataset) :
numerical expression has 14 elements: only the first used

In the for loop, did you mean to say 1:length(titanicDataset)?

data.frames have dimensions ; some number of columns, some number of rows.
Decide what you want to loop over; lets say rows. use ncol() or nrow() to get a number for that.
nrow(titanicDataset)

you want a sequence going from (if there is one) the first row to that last row. so use seq_len()
i.e.

for ( i in seq_len(nrow(titanicDataset)) {

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.