Ayoze Alfageme
Ayoze Alfageme

Reputation: 311

Extract from data frame rowas based on values of other columns

I would like to extract the rows based on the values of the column year (see below for data). For instance, I would like to extract saying from 1980 to 1985 and from 1990 to 1995.

dput(malineGDP)
structure(list(Year = c(1980, 1981, 1982, 1983, 1984, 1985, 1986, 
1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 
2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 
2020, 2021), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L), levels = "GDPpercent", class = "factor"), value = c(0.0277183930261643, 
0.0288427846071515, 0.0526348961735552, 0.0371487738221672, 0.0427232519007513, 
0.0704405101613155, 0.0771983341458076, 0.07685960434821, 0.111917681446816, 
0.082616933786008, 0.0426218080075034, 0.0287408712637852, 0.0283927466984115, 
0.0463085646932952, 0.0569077180354995, 0.0872515547548894, 0.0929491742150426, 
0.130132692280228, 0.200424443096016, 0.222006216429481, 0.191768530376496, 
0.0955005462614614, 0.0476287715422711, 0.0583828349263007, 0.0823773327852261, 
0.102928117429317, 0.133464508881022, 0.135900867106755, 0.0822682054263, 
0.0606165184312332, 0.0652403453525391, 0.0799398361449388, 0.0612558039666617, 
0.0721234864232935, 0.122718837613643, 0.132779681405992, 0.0954672321123404, 
0.0904404973441826, 0.0940829197015593, 0.0882826864405067, 0.0534565360036942, 
0.11095822366049)), row.names = c(NA, -42L), class = "data.frame")

I could'nt figure out how

Upvotes: 1

Views: 21

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61214

A combination of %in% and filter:

library(dplyr)
df %>% 
  filter(Year %in% c(1980:1985, 1990:1995))
 Year   variable      value
1  1980 GDPpercent 0.02771839
2  1981 GDPpercent 0.02884278
3  1982 GDPpercent 0.05263490
4  1983 GDPpercent 0.03714877
5  1984 GDPpercent 0.04272325
6  1985 GDPpercent 0.07044051
7  1990 GDPpercent 0.04262181
8  1991 GDPpercent 0.02874087
9  1992 GDPpercent 0.02839275
10 1993 GDPpercent 0.04630856
11 1994 GDPpercent 0.05690772
12 1995 GDPpercent 0.08725155

Same result using R base

subset(df, Year %in% c(1980:1985, 1990:1995))

Anohter R base approach

df[df$Year %in% c(1980:1985, 1990:1995) , ]

Upvotes: 1

Related Questions