Search code examples
rsubsetr-factor

How to create a vector with the values of a data frame classified by factors in R?


I have a data frame with values classified by levels (factors), so I want to create a vector with the values of an specific level, e.g.

A <- c("Case1", "Case3", "Case2", "Case3", "Case2",
       "Case1", "Case3", "Case2", "Case2", "Case3",
       "Case1", "Case1", "Case3", "Case1", "Case2")
Factors <- factor(A)
Values <- 1:15

DF <- data.frame(Factors, Values)

Values_of_Case1 <- DF$Values... ????

How to create a vector in order to obtain something like:

print(Values_of_Case1)
[1]  1  6 11 12 14

Solution

  • DF$Values[DF$Factors == "Case1"]
    [1]  1  6 11 12 14
    

    or

    subset(DF, Factors=='Case1')$Values
    [1]  1  6 11 12 14
    

    should work.

    If you wanted only the row index for the matches you could do:

    which(DF$Factors == "Case1")
    [1]  1  6 11 12 14
    

    Which in this case is the same, but it might not be in your use case.