mercredi 28 juillet 2021

How to produce an if statement to compare rows in R

I need to compare two rows next to each other in a column in a dataframe, if the data in both those rows matches, then save the most recent row, e.g.

Column: Animals

# 1  dog  row 1

# 2  cat  row 2

# 3  cat  row 3

It should compare dog and cat, then not save any data. So it won't save row 1 and 2.

But when it moves onto compare cat and cat, realise they are the same and save those rows. So save rows 2 and 3. As they are the same. I need to do this for lots of rows, iterating through to compare a big set of data.

I've tried to produce an if statement in which:

#  if(data$Animals[i] == data$Animals[i+1]) {
#    print(data$Animals[i])
#  }
# }

I want to save the printed output into a new dataframe, but I'm not sure how to go about it.

I'm new to R and learning, please help anyway you can, I'd appreciate it :)

Aucun commentaire:

Enregistrer un commentaire