0
votes

I am working on a rather large dataset in R, containing a continuous numeric variable. In another dataset, I have named intervals, described by min and max values, that I want to apply to the continuous variable in my large dataset.

Below is some example code:

df<-data.frame(x=c(1:6))    
groups<-data.frame(cat=c("a","b","c","d"), min=c(1,2,4,6), max=c(2,4,5,8))

I want to make a new column, df$cat, so that the values of df$x are within the min-max boudaries found in the groups data frame. Ideally, I would like to have groups$min >= df$x > groups$max.

> df
  x cat
1 1   a
2 2   b
3 3   b
4 4   c
5 5   d
6 6   d

Is there any easy way of doing this?

2
you want something easier than a loop over groups? - user31264
shouldn't 5 correspond to nothing here, since d goes to 6 and 7 while c goes to 4? - Psidom

2 Answers

2
votes

Set up data:

df <- data.frame(x=c(1:6))    
groups <- data.frame(cat=c("a","b","c","d"), min=c(1,2,4,6), max=c(2,4,5,8))

Use cut() with the labels argument specified:

brks <- c(groups$min,tail(groups$max,1))
df$cat <- cut(df$x,breaks=brks,labels=groups$cat,right=FALSE)
0
votes
df<-data.frame(x=c(1:6))
groups<-data.frame(cat=c("a","b","c","d"), min=c(1,2,4,6), max=c(2,4,5,8))

for(i in 1:nrow(groups)){

  numbers_in_range = df$x[df$x >= groups[i,]$min & df$x <= groups[i,]$max]
  df[,i+1] = df$x %in% numbers_in_range
  colnames(df)[2:ncol(df)] = as.character(groups$cat)

}

something like this will tell you which numbers are in which groups ranges. Is this what you were after?