How to use index to find value of given year

Hi!

I have a table with the columns: 1) year 2) import 3) export I am supposed to use indexing to find the value of imports in e.g. 2000 and 2005.
I am then supposed to assign these values to a new object using the concatenate function. How would I do this?

I've started with the following:

trade_data$import[2000]

However, this doesn't work. But if I for example us 1 instead, it will take the first year in the column. Is it possible to do so, that I can just write in the year I want to index?

Thanks in advance!

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

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.