Search code examples
rrecode

R: Replace various values by their group


I want to recode a vector x with individuals by their group.

set.seed(1)
x<-sample(135,2000,rep=T)
individuals<-1:135
groups<-sample(7,135,rep=T)

I've tried this, but it doesn't seem to work if there's a expression at the left side of each equal sign, only if there's an explicit vector e.g. c(7,12,29,31).

x_recod<-car::recode(x,"individuals[groups=='1']=1;individuals[groups=='2']=2;individuals[groups=='3']=3;individuals[groups=='4']=4;individuals[groups=='5']=5;individuals[groups=='6']=6;individuals[groups=='7']=7")

Also I wonder if there's a way to do this without having to mention every group.

Editing: The solution to this example is trivial because those are x is a numeric vector, but what if it's characters? E.g.

x<-sample(letters,2000,rep=T)
individuals<-letters
groups<-sample(7,26,rep=T)

Solution

  • You can use x to subset groups.

    newx <- groups[x]
    

    Verify the output :

    head(x)
    #[1]  68 129  43  14  51  85
    groups[head(x)]
    #[1] 6 7 2 3 7 7
    head(newx)
    #[1] 6 7 2 3 7 7