There are several ways to achieve this. To select data you can either provide indices or logical vectors, since you are interested in data where a condition is met, the latter is suitable.
The code you posted does not work as intended, because in that case you are requesting the 2000th item in the import
column.
Let's first generate some example data.
set.seed(79696) # makes the rnorm output reproducible
example <- data.frame(
year = c(2000:2019),
imports = rnorm(20),
exports = rnorm(20))
example[example$year == 2000, "imports"]
#> [1] -2.084291
This should lead to the value for imports in 2000 being returned.
Of course you can match for several years as well.
example[example$year %in% c(2000:2005), "imports"]
#> [1] -2.0842908 1.5329676 -0.2391197 -0.5155621 2.0700904 -3.7933744
If you want to include the years as well, this is straightforward.
example[example$year %in% c(2000:2005), c("year", "imports")]
#> year imports
#> 1 2000 -2.0842908
#> 2 2001 1.5329676
#> 3 2002 -0.2391197
#> 4 2003 -0.5155621
#> 5 2004 2.0700904
#> 6 2005 -3.7933744
If you want to include all columns, then just remove the c("year", "imports")
part (but leave the comma before it).
Of course there is also a way to do this using tidyverse
packages. Note that these will always return a data.frame.
For one year:
example %>%
filter(year == 2000) %>%
select(imports)
#> imports
#> 1 -2.084291
Many years:
example %>%
filter(year %in% c(2000:2005)) %>%
select(imports)
#> imports
#> 1 -2.0842908
#> 2 1.5329676
#> 3 -0.2391197
#> 4 -0.5155621
#> 5 2.0700904
#> 6 -3.7933744
And of course you are free to choose multiple columns (if you omit the call to select you get all columns by default).
example %>%
filter(year %in% c(2000:2005)) %>%
select(year, imports)
#> year imports
#> 1 2000 -2.0842908
#> 2 2001 1.5329676
#> 3 2002 -0.2391197
#> 4 2003 -0.5155621
#> 5 2004 2.0700904
#> 6 2005 -3.7933744