Search code examples
rnameslevels

How do I isolate a level as its own variable in R?


Within the dataset "PlantGrowth" there is only two variables, group and weight.

data("PlantGrowth")
names(PlantGrowth)
[1] "weight" "group" 

The variable "group" 3 levels

levels(PlantGrowth$group) 
[1] "ctrl" "trt1" "trt2"

I want to be able to call the control and treatments of the variable "group" but I can't figure out how to separate them into their own variable. I've renamed the levels to:

levels(PlantGrowth$group) <- c("control","treatment1","treatment2")

But now I want to be able to analyze control against treatment 1 and 2. I've tried a bunch of different things like this:

control <- (PlantGrowth$group$control)


Error in PlantGrowth$group$control : 
$ operator is invalid for atomic vectors

Obviously that is incorrect though Thank you!


Solution

  • Is this what you want? (using filter from dplyr)

    control <- PlantGrowth %>% filter(group == "control")
    

    if you want you can also split your whole data frame by "group", like so:

    split(PlantGrowth, PlantGrowth$group)