Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove row conditionally from data frame

Tags:

r

How can I remove rows conditionally from a data table?

For example, I have:

Apple, 2001
Apple, 2002
Apple, 2003
Apple, 2004
Banana, 2001
Banana, 2002
Banana, 2003
Candy, 2001
Candy, 2002
Candy, 2003
Candy, 2004
Dog, 2001
Dog, 2002
Dog, 2004
Water, 2002
Water, 2003
Water, 2004

Then, I want to include only the rows with 2001-2004 per group, i.e.:

Apple, 2001
Apple, 2002
Apple, 2003
Apple, 2004
Candy, 2001
Candy, 2002
Candy, 2003
Candy, 2004
like image 561
Polo Avatar asked Jun 28 '26 05:06

Polo


1 Answers

Using data.table, check if all the 2001:2004 are present %in% the 'year' column for each group of 'Col1', then get the Subset of Data.table

library(data.table)
setDT(df1)[, if(all(2001:2004 %in% year)) .SD, by = Col1]
#    Col1 year
#1: Apple 2001
#2: Apple 2002
#3: Apple 2003
#4: Apple 2004
#5: Candy 2001
#6: Candy 2002
#7: Candy 2003
#8: Candy 2004

data

df1 <- structure(list(Col1 = c("Apple", "Apple", "Apple", "Apple", "Banana", 
"Banana", "Banana", "Candy", "Candy", "Candy", "Candy", "Dog", 
"Dog", "Dog", "Water", "Water", "Water"), year = c(2001L, 2002L, 
 2003L, 2004L, 2001L, 2002L, 2003L, 2001L, 2002L, 2003L, 2004L, 
 2001L, 2002L, 2004L, 2002L, 2003L, 2004L)), .Names = c("Col1", 
 "year"), class = "data.frame", row.names = c(NA, -17L))
like image 156
akrun Avatar answered Jun 30 '26 01:06

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!