user7535248
user7535248

Reputation: 11

R: Assign certain items of a variable into defined groups

Let's say I've a variable with 594 different items.

[1] "qwerty"
[2] "qwerta"
[3] "qwerto"
[4] "qwerte"
etc.

What I'd like to achieve is to group the items into new predefined categories. For example, the items ranging from levels [1] to [85] belong to category "A":

    workclas<-factor(levels=c("A", "B", "C"), ordered=T)
    workclas[levels(x)>=1 & levels(x)<85]<-"A"
    workclas[levels(x)>=85 & levels(x)<272]<-"B"
    workclas[levels(x)>=272 & levels(x)<594]<-"C"
    workclas[x=="Refusal" | x=="Don't know" | x=="No answer"]<-NA
    table(workclas, exclude=NULL)

I was thinking of 'aggregate' but that doesn't work obviously.

    aggregate(formula, data, FUN, ...,
    subset, na.action = na.omit)

Also I can't use 'split' since I don't have a reocurring and identical element to split by.

    split(x, f, drop = FALSE, sep = ".", lex.order = FALSE, ...)
    split(x, f, drop = FALSE, ...) <- value

How would I solve this in R?

Thank you for your efforts!

Thomas

Upvotes: 0

Views: 36

Answers (1)

user7535248
user7535248

Reputation: 11

The short input of User A. Webb was much appreciated. This is what I did, if anyone else is struggling with a similar problem:

workisco<-as.numeric(workisco)
workclas<-factor(levels=c("A", "B", "C", "D"), ordered=T)
workisco = cut(workisco, 
    breaks = c(1,171,279,590),
    labels = workclas,
    right = TRUE)

Upvotes: 1

Related Questions