Search code examples
rdataframetidyversetibble

Tidyverse approach to selecting values from different columns in a dataframe with row-column index pairs


In R, I have a character vector v, whose values are all elements of colnames(rain) for a dataframe rain. I want to use v to create a new vector chosen whose values satisfy chosen[i] == rain[i, v[i]] without resorting to a loop and preferably using a tidyverse approach.

For example, if I have:

library(tidyverse)
rain <- tibble(ceres = c(0, 1, 0, 1.5, 3),
               mond = c(0, 0, 0.5, 0, 0),
               els = c(1, 2, 1, 0, 1))

v <- c("els", "ceres", "els", "mond", "ceres")

I would want to have returned in chosen:

> chosen
# els ceres   els  mond ceres 
#    1     1     1     0     3

Solution

  • You could do

    rain %>%
      mutate(id = row_number()) %>%
      pivot_longer(-id) %>%
      inner_join(tibble(id = seq_along(v), name = v)) 
    

    which returns

    # A tibble: 5 x 3
         id name  value
      <int> <chr> <dbl>
    1     1 els       1
    2     2 ceres     1
    3     3 els       1
    4     4 mond      0
    5     5 ceres     3
    

    Adding

    pull(value, name)
    

    returns the named vector

    #>  els ceres   els  mond ceres 
    #>    1     1     1     0     3