How to convert from category to numeric in r

后端 未结 3 693
一个人的身影
一个人的身影 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:22

    Hopefully category is a factor variable. If not, convert it to factor:

    category <- as.factor(category)
    

    You could use the relevel function to assigned level 1 to the category "dog" as follows:

    levels(category) <- relevel(category, ref = "dog")
    

    and then create a data frame using following code:

    df <- data.frame(category,as.numeric(category))
    colnames(df) <- c("category","rank")
    

    as.numeric function returns the levels of the factors which is the rank in your case.

提交回复
热议问题