Search code examples
rdataframe

dynamically extracting an element from a dataframe in R


I have a data frame and I want to call a specific column with specific values.

Like this:

the.dataframe <- data.frame(
  partner=c("rather not say", "male", "female", 
            "non-binary", "gender not listed"),
  gender=c("male", "female", "non-binary", 
           "gender not listed", "rather not say"),
  response.01=c(TRUE, FALSE, TRUE, FALSE, TRUE),
  response.02=c(1, 2, 3, 4, 5)
)

the.dataframe$gender[the.dataframe$gender=="male"]
# [1] "male

What I have been unable to do is to make it so I can change the gender variable dynamically since the $ can't use objects:

x <- "gender"
subset(the.dataframe, x == "male", select = x)
# [1] gender
# <0 rows> (or 0-length row.names)

Solution

  • Alternale version of above if you want to access other columns too.

    colname <- "gender"
    df[df[,colname] == "male",colname]