1

I am a beginner at R and searched the forums and did not find an answer to this question. I am trying to create a loop in R that counts whether a condition is met between 2 rows in a dataframe. I understand that this is not an efficient way to do this but it is for a class assignment. My problem is that my code is creating an endless loop rather giving me the counter output and it is unclear to me how to fix it. I would greatly appreciate any suggestion. The code is below:

counter=0
for (i in 1:nrow(dataframe))
  {if (dataframe$column1[i]>dataframe$column2[i]==TRUE)
{
counter=counter+1}
}
print(counter)
1
  • There's nothing obviously wrong with the code, but it would be helpful if you could share the dataframe as well. Commented Mar 25, 2017 at 17:10

1 Answer 1

1

If you just want to know how many times your column 1 is higher than column 2, you don't have to use a loop :

counter <- sum(dataframe$column1>dataframe$column2)

sum(dataframe$column1>dataframe$column2) gives you a vector of length nrow(dataframe) with TRUE and FALSE when the condition is verified, and R do this element by element with vectores.

Then when you sum it, TRUE is considered as a 1 and FALSE as a 0. So it gives you how many times the condition is verified beetween the two columns.

Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate the concise solution using the sum command but I need to do this assignment using control flow which is why I was using a loop. The columns in the dataframe that I am referencing have both numbers and empty values. I modified the code above by putting a print(counter) statement in the line below the counter =counter+1 but when I run the loop I get no output rather than the current counter. It is unclear to me what I am doing wrong so would greatly appreciate any additional suggestions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.