Grab A Specific Row From Frame Where Column 1 == Column 2

I have a data frame that looks very similar to this, I would like some help writing a script where when column 1 == column 2 grab that whole row and output it.

myNewSample <- data.frame(
  Column_1 = c('Green 1', 'Green 2', 'Sum', 'Green 1', 'Green 2', 'Sum','Green 1', 'Green 2', 'Sum'),
  Column_2 = c('Yes', 'No', 'Sum', 'Yes', 'No', 'Sum', 'Yes', 'No', 'Sum'),
  Column_3 = c('Expected', 'Expected', 'Expected', 'Not E', 'Not E', 'Not E', 'Sum', 'Sum', 'Sum'),
  Column_4 = c('X', 'X','X', 'X','X', 'X','X', 'X','X')
)

The context behind this is I am looking to output my result table into a markdown file however I just need that specific part of the result table. Because the result table is always changing having it grab where column 1 == sum and in that sum row column 2 == sum grab the whole row. As we can see that X value would be the result so I can then grab the whole value from there.

Ideally something in a if statement or for loop would be ideal because of the ever changing result table by it looking where sum == sum this piece of script can be reused through the program

I am looking to get:

Sum + Sum + Expected

Sum + Sum + Not E

Sum + Sum + Sum

Thanks.

myNewSample <- data.frame(
  Column_1 = c('Green 1', 'Green 2', 'Sum', 'Green 1', 'Green 2', 'Sum','Green 1', 'Green 2', 'Sum'),
  Column_2 = c('Yes', 'No', 'Sum', 'Yes', 'No', 'Sum', 'Yes', 'No', 'Sum'),
  Column_3 = c('Expected', 'Expected', 'Expected', 'Not E', 'Not E', 'Not E', 'Sum', 'Sum', 'Sum'),
  Column_4 = c('X', 'X','X', 'X','X', 'X','X', 'X','X'),
  stringsAsFactors = FALSE
)

dplyr::filter(myNewSample,
       Column_1==Column_2)

Hi Sustainer, thanks for your reply. Are you sure this is how it is supposed to work. When I try this is an error I get

Error in Ops.factor(Column_1, Column_2) : 
  level sets of factors are different

when making the example data.frame , i used stringsAsFactors, as my way of working with character fields, rather than factors.
What are your requirements regarding, the column data types ?

Easier solution:

filter(df, Column_1 == "Sum" & Column_2 == "Sum")

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.