for loop & if function in R

后端 未结 3 1596
刺人心
刺人心 2021-01-27 19:22

I was writing a loop with if function in R. The table is like below:

ID  category
1   a
1   b
1   c
2   a
2   b
3   a
3   b
4   a
5   a

I want

3条回答
  •  执笔经年
    2021-01-27 19:36

    what you want is actually a column of factor level. do this

    df$count=as.numeric(df$category)
    

    this will give out put as

      ID category count
    1  1        a     1
    2  1        b     2
    3  1        c     3
    4  2        a     1
    5  2        b     2
    6  3        a     1
    7  3        b     2
    8  4        a     1
    9  5        a     1
    

    provided your category is already a factor. if not first convert to factor

    df$category=as.factor(df$category)
    df$count=as.numeric(df$category)
    

提交回复
热议问题