[R] Establishing groups using something other than ifelse()

Sam Albers tonightsthenight at gmail.com
Fri Jan 20 00:05:18 CET 2012


Hello all,

This is one of those "Is there a better way to do this questions". Say
I have a dataframe (df) with a grouping variable (z). This is my base
data. Now I know that there is a higher order level of grouping that
exist for my group variable. So what I want to do is create a new
column that express that higher order level of grouping based on
values in the sub-group (z  in this case). In the past I have used
ifelse() but this tends to get fairly redundant and messy with a large
amount of sub-groupings (z). I've created a sample dataset below. Can
anyone recommend a better way of achieving what I am currently
achieving with ifelse()? A long series of ifelse statements makes me
think that there is something better for this.

## Dataframe creation
df <- data.frame(x=runif(36, 0, 120),
                       y=runif(36, 0, 120),

z=factor(c("A1","A1","A2","A2","B1","B1","B2","B2","C1","C","C2","C2"))
                       )

## Current method is grouping
df$Big.Group <- with(df, ifelse(df$z=="A1","A", ifelse(df$z=="A2","A",
ifelse(df$z=="B1", "B", ifelse(df$z=="B2", "B", "C")))))


So any suggestions? Thanks in advance!

Sam



More information about the R-help mailing list