0

Say I have a single column in table1 that looks like this

Category
1
3
2

I want to create a new column called Score, and have the corresponding value of 5, 10, 25 assigned to the categories 1 , 2, and 3, and retained as a numeric value.

So the final outcome would be:

Category | Score
1 | 5
3 | 25
2 | 10

I wrote this:

table1$score= factor(table1$Category, labels = c("5", "10", "25"))

But this produced a factor, so I ended up doing

table1$score= as.numeric(factor(table1$Category, labels = c("5", "10", "25")))

Which is pretty clunky...is there a more elegant way of doing it?

I've also tried using a string of ifelse functions which worked, but was extremely clunky.

Thanks!

  • 1
    `table1$Score <- dplyr::recode(table1$Category, '1' = 5, '2' = 10, '3' = 25)` – Ronak Shah Feb 04 '21 at 04:39
  • *"value of 5 ... retained as a numeric value"* is not compatible with `factor`s; that is, `levels` of factors are strings, not numbers, and I suggest that the best way to do this does not involve `as.integer`ing it each time you want to use it as such. – r2evans Feb 04 '21 at 04:42
  • Base R version of @RonakShah's comment: `sapply(table1$Category, switch, '1' = 5, '2' = 10, '3' = 25)`. – r2evans Feb 04 '21 at 04:45

0 Answers0