How to convert from category to numeric in r

后端 未结 3 694
一个人的身影
一个人的身影 2021-01-13 00:45

Here is my problem:

I have a table with categories and I want to rank them:

category
dog
cat
fish
dog
dog

What I want is to add

3条回答
  •  走了就别回头了
    2021-01-13 01:24

    I assume that if you write "ranks" you mean ranks. I further assume you want to rank according to number of occurrence.

    cats <- factor(c("dog", "cat", "fish", "dog", "dog"))
    
    #see help("rank") for other possibilities to break ties
    ranks <- rank(-table(cats), ties.method="first")
    
    DF <- data.frame(category=cats, rank=ranks[as.character(cats)])
    
    print(DF)
    #   category rank
    # 1      dog    1
    # 2      cat    2
    # 3     fish    3
    # 4      dog    1
    # 5      dog    1
    

提交回复
热议问题