How to remove rows from a data frame based on a subset function?

I would like to remove some rows from my data frame. I think using subset is the easiest way to do this.

I used the code below to remove some of the lines before:

 data_selected <- subset(tbl_data, Name.x != "XXX" & Name.y != "YYY") 

The question is how to remove rows from my table that have the same row in two cells (one row).

I think mtcars can be used as an example:

  mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 

gear and carb can use columns. As you can see, the first two rows must be removed from this data, because both have the same value 4 in these two columns. Please log in to the account that in my data I have no numerical values, except for a character string.

+5
source share
1 answer

Based on the information in the post, I think a comparison ( != ) Between the "gear" and "carb" columns would be sufficient for a subset of the dataset

 df1 <- mtcars[1:5,] subset(df1, gear!=carb) # mpg cyl disp hp drat wt qsec vs am gear carb #Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 #Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 #Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 

This should also work for non-numeric columns, but not for partial matches.

If we need to make an exception due to saving lines that have as "Unknown", we can use the | after adding another logical condition (`(gear == 'Unknown' and carb == 'Unknown')) to the original state.

Making some changes to the data set to display the output (as an example, I know that I am changing the numeric column to character by doing this)

  df1$gear[4] <- 'Unknown' df1$carb[4] <- 'Unknown' df1$gear[5] <- 'Unknown' subset(df1, (gear=='Unknown' & carb=='Unknown') | gear!=carb) # mpg cyl disp hp drat wt qsec vs am gear carb #Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 #Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 Unknown Unknown #Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 Unknown 2 
+3
source

All Articles