Search code examples
rdataframemodeling

Grabs rows where second column is equal to value


I have a dataset which looks something like this:

print(animals_in_zoo)

// I only know the name of the first column, the second one is dynamic/based on a previously calculated variable 
animals | dynamic_column_name

// What the data looks like
elefant x
turtle
monkey
giraffe x
swan
tiger   x

What I want is to collect the rows in which the second columns' value is equal to "x".

What I want to do is something like:

SELECT * from data where col2 == "x";

After that, I want to grab only the first column and create a string object like "elefant giraffe tiger", but that is the easy part.


Solution

  • You can reference that column by its index and use that to get the animals you want:

    df1 <- structure(list(animal = c("elefant", "turtle", "monkey", "giraffe", 
                                     "swan", "tiger"), dynamic_column = c("x", NA, NA, "x", NA, "x"
                                     )), row.names = c(NA, -6L), class = "data.frame")
    
    df1[, 1][df1[, 2] == "x" & !is.na(df1[, 2])]
    #> [1] "elefant" "giraffe" "tiger"