filter out the rows where two specific columns are not equal in r

You can filter out the rows where two specific columns are not equal in R by using the dplyr library or base R. Here's how you can do it:

main.r
# Load the dplyr library
library(dplyr)

# Create a sample DataFrame
df <- data.frame(
  column1 = c(1, 2, 3, 4, 5),
  column2 = c(1, 3, 3, 5, 6)
)

# Filter out the rows where column1 and column2 are not equal
filtered_df <- df %>% 
  filter(column1 != column2)

# Print the filtered DataFrame
print(filtered_df)

# Alternatively, you can use base R
filtered_df_base_r <- df[df$column1 != df$column2, ]

# Print the filtered DataFrame
print(filtered_df_base_r)
462 chars
22 lines

In the above code:

  1. We create a sample DataFrame df with two columns.
  2. We use the filter function from the dplyr library to filter out the rows where column1 and column2 are not equal. The filter function returns a new DataFrame filtered_df.
  3. We print the filtered_df to see the result.
  4. Alternatively, we use base R to achieve the same result. The expression df$column1 != df$column2 creates a logical vector that is used to subset the rows of the DataFrame.

related categories

gistlibby LogSnag