how bout

levels(df$z)[grep('A',levels(df$z))] <- 'A'
levels(df$z)[grep('B',levels(df$z))] <- 'B'
levels(df$z)[grep('C',levels(df$z))] <- 'C'

does that do what you're wanting?


On Thu, Jan 19, 2012 at 3:05 PM, Sam Albers <tonightstheni...@gmail.com>wrote:

> 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
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to