Hi
I have 2 data frames: the 1st includes numeric values (x column), and the 2nd set of ranges with unique IDs
I would like to add the 1st df a column for group ID, with default NA (which means - no group). For rows which df$x fall within a range - I want to set the group ID
df1<-data.frame(x=c(68, 39, 1, 34, 87, 43, 14, 82, 59, 21))
df.ranges<-data.frame(group=c("A", "B", "C"),
from=c(40, 20, 80),
to=c(70, 30, 90))
df1$group<-NA
I can do it with for loop
library(dplyr)
#expected results
for (i in 1:length(df.ranges$group)){
df1$group[which(between(df1$x, df.ranges$from[i], df.ranges$to[i]))]<-levels(factor(df.ranges$group[i]))
}
df1
but I wondered if there is a vectorization method to do it (without loop) ?