0

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)
1
  • 4
    Are you just trying to count how many times userid is equal to 1? sum(generaldf$userid == 1) will do that without a for loop Commented Jun 28, 2017 at 14:06

2 Answers 2

1

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.

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

2 Comments

thank you! it works for counting, but if i want to put a function under a for loop, what is the best syntax to use ?
you can use it in the function; it does not make much sense though. You are outsourcing to a function the job of a single line of code; not very efficient. But if you must: either make the sum the last operation of the function before the final curly brace (your function will return the last value and end), or call return(y) from within the curly braces (your function will return this value and stop execution). These are two slightly different means to the same end.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.