subsetting a dataframe by existing object

Viewed 37

I have a predefined object grade <- "G3". I would like to subset a data frame by grabbing 3 from "grade" object, subsetting only grade 3.

Here is an example of data

id <- c(1,2,3,4,5)
grade <- c(3,3,4,4,5)
score <- c(10,5,10,5,10)


data <- data.frame("id"=id,"grade"=grade, "score"=score)

> data
  id grade score
1  1     3    10
2  2     3     5
3  3     4    10
4  4     4     5
5  5     5    10

I would like to get something like this:

  > data
      id grade score
    1  1     3    10
    2  2     3     5

Thanks!

3 Answers

With tidyverse, we can use !! to check for the 'grade' object in the global environment instead of the column in the 'data' environment, remove the 'G' and do a ==

library(dplyr)
library(stringr)
data %>%
    filter(grade == str_remove(!!grade, "G"))
#  id grade score
#1  1     3    10
#2  2     3     5

You can use filter, but you would likely want to change the object name so it doesn't match the variable name.

Grade <- "G3"

data <- data.frame("id"=id,"grade"=grade, "score"=score) %>%
  filter(paste0("G", grade) == Grade)

You can use readr's parse_number to extract digits from a string with a minimum of fuss, and then subset with the result:

library(readr)

data[data$grade == parse_number(grade),]

Or with base R's sub replace non-numbers with "":

data[data$grade == sub("[^0-9]", "", grade),]

Or if the only other character in your string is always "G" then:

data[data$grade == sub("G", "", grade),]
Related