Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Categorizing Values in a data.frame

I have the following sample data frame:

> df <- data.frame(v=c("a", "a", "b", "b", "c", "d", "d"))
> df
  v 
1 a 
2 a 
3 b 
4 b 
5 c 
6 d 
7 d 

I would like to categorize these values in a separate column based on some arbitrary mapping. For example:

  • a -> x
  • b -> x
  • c -> y
  • d -> y

So afterwards, I would have the following:

  v cat
1 a   x
2 a   x
3 b   x
4 b   x
5 c   y
6 d   y
7 d   y

Thank you

like image 208
oneself Avatar asked Dec 12 '25 13:12

oneself


1 Answers

Here's one option:

create a named vector with the mapping:

x <- c(a = "x", b = "x", c = "y", d = "y")

Then add the new column using the named vector:

df$cat <- x[df$v]
df
#  v cat
#1 a   x
#2 a   x
#3 b   x
#4 b   x
#5 c   y
#6 d   y
#7 d   y
like image 197
talat Avatar answered Dec 14 '25 03:12

talat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!