chayma
chayma

Reputation: 3

How to use if in a for loop in R

I am trying to compute the occurrence of a line in a dataframe, but I don’t get the result expected.

ps: generaldf is a data.frame, and userid is a column of integer

y<-0

        for(i in seq_len(nrow(generaldf))) 
        {
          if (generaldf$userid==1) 
            y <-y+1
        }

 return(y)

Upvotes: 0

Views: 236

Answers (2)

Florent Angly
Florent Angly

Reputation: 515

Your post does not contain a question. Also, your example is not reproducible without the data.

Despite this, it seems that your problem is generaldf$userid==1. By subsetting the dataframe with generaldf$userid, you get an entire column (a vector), not the single value that you assumed.

You probably need to learn a bit more about dataframes. Have a look at a tutorial or two.

PS/ Avoiding the loop as Jindra Lacko suggested, is the method I would use to count occurrences.

Upvotes: 0

Jindra Lacko
Jindra Lacko

Reputation: 8699

To make your code work get rid of the return(y). return() is for functions. Here you can just print the result. Either print(y) or just (y)

Instead of the for loop consider summing the logical vector (true = 1, false = 0) mentioned in the comments sum(generaldf$userid == 1) - it is a more elegant solution.

Upvotes: 1

Related Questions