Running count based on field in R

后端 未结 3 1880
长情又很酷
长情又很酷 2021-02-15 13:33

I have a data set of this format

User       
1 
2
3
2
3
1  
1      

Now I want to add a column saying count which counts the occurrence of the

3条回答
  •  长发绾君心
    2021-02-15 14:08

    An option using dplyr

     library(dplyr)
     df1 %>%
          group_by(User) %>%
          mutate(Count=row_number())
     #    User Count
     #1    1     1
     #2    2     1
     #3    3     1
     #4    2     2
     #5    3     2
     #6    1     2
     #7    1     3
    

    Using sqldf

    library(sqldf)
    sqldf('select a.*, 
               count(*) as Count
               from df1 a, df1 b
               where a.User = b.User and b.rowid <= a.rowid
               group by a.rowid')
    #   User Count
    #1    1     1
    #2    2     1
    #3    3     1
    #4    2     2
    #5    3     2
    #6    1     2
    #7    1     3
    

提交回复
热议问题