Reputation: 3
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
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
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