Reputation: 3384
data1=data.frame("Score"=c(1,3,4,4,4,5,6,6,6,6,6),
"Group"=c(1,1,2,2,2,2,3,3,3,3,3),
"Group1"=c('Cat','Cat','Fox','Fox','Fox','Fox','Dog','Dog','Dog','Dog','Dog'))
I have 'data1' with just score. I wish to add Group and Group 1. The rules are:
If 0 <= score <= 1, Group = 1, GrouopLabel = Cat
If 2 <= score <= 4, Group = 2, GrouopLabel = Fox
If 5 <= score <= 10, Group = 3, GrouopLabel = Dog
Upvotes: 1
Views: 408
Reputation: 886938
We can use cut
to create the 'Group', then based on the numeric index of 'Group', replace the values to 'Cat', 'Fox', 'Dog' in 'Group1'
library(data.table)
setDT(data1)[, Group := as.integer(cut(Score, breaks = c(-Inf, 1, 4, 10)))][,
Group1 := c('Cat', 'Fox', 'Dog')[Group]][]
Upvotes: 2