Search code examples
rdataframeloopsvector

Extract value of cell from each column, where row value matches value in vector


I have a vector of years (97). I also have a data frame with "year" and 97 columns of values.

Year 1
2020 5.663
2021 9.344

vector (97): 2050, 2045, 2047 ......

For column 1 I need to extract the value of the first year of the vector, 2050, for column 2 the second value of the vector, 2045, etc..

dataframe

I'm not sure how to do this, I thought maybe a loop would be best?


Solution

  • I may have misunderstood; is this your expected output?

    set.seed(123)
    df <- data.frame(Year = c(2020, 2021, 2022),
                     Col1 = rnorm(3),
                     Col2 = rnorm(3),
                     Col3 = rnorm(3))
    df
    #>   Year       Col1       Col2       Col3
    #> 1 2020 -0.5604756 0.07050839  0.4609162
    #> 2 2021 -0.2301775 0.12928774 -1.2650612
    #> 3 2022  1.5587083 1.71506499 -0.6868529
    
    years_vec <- c(2022, 2021)
    
    output <- list()
    for (i in seq_along(years_vec)) {
      output[[i]] <- df[match(years_vec[i], df$Year), i + 1]
    }
    unlist(output)
    #> [1] 1.5587083 0.1292877
    

    Created on 2023-06-28 with reprex v2.0.2