Elsybelsy
Elsybelsy

Reputation: 71

Remove rows with identical values based off another variable in row

I have a dataset that looks like this:

    1      2
   amt1     3
   amt2     3
   amt3     3
   amt1     2
   amt2     2
   amt2     2
   nrt1     1
   nrt1     1
   nrt1     1

I'm trying to delete rows where there is no variety in column 1. So in the example above, the rows with 3 and 2 would all stay, but I would delete the rows for 1.

I can't figure out a way to conditionally search based on one column and delete the other depending on every row.

Upvotes: 2

Views: 246

Answers (3)

Using Dplyr: df%>% if_else(as. numeric(1-lag(1)==0)&2-lag(2)==0,na,df). na.omit(df)

Upvotes: 0

manotheshark
manotheshark

Reputation: 4357

Using base R

unique(df1)

    X1 X2
1 amt1  3
2 amt2  3
3 amt3  3
4 amt1  2
5 amt2  2
7 nrt1  1

Upvotes: 2

akrun
akrun

Reputation: 887118

Here is an option with dplyr. Grouped by the second column, we can filterthe groups having more than one unique value in first column (assuming that it is a data.frame)

library(dplyr)
df1 %>%
   group_by(`2`) %>%
   filter(n_distinct(`1`) > 1)

Upvotes: 2

Related Questions