How to use column indices to collect values from columns in R

Viewed 59
x y z column_indices 
6 7 1      1,2
5 4 2       3
1 3 2      1,3

I have the column indices of the values I would like to collect in a separate column like so, what I want to create is something like this:

x y z column_indices values
6 7 1      1,2        6,7
5 4 2       3          2
1 3 2      1,3        1,2

What is the simplest way to do this in R?

Thanks!

2 Answers

In base R, we can use apply, split the column_indices on ',', convert them to integer and get the corresponding value from the row.

df$values <- apply(df, 1, function(x) {
   inds <- as.integer(strsplit(x[4], ',')[[1]])
   toString(x[inds])
})

df
#  x y z column_indices values
#1 6 7 1            1,2   6, 7
#2 5 4 2              3      2
#3 1 3 2            1,3   1, 2

data

df <- structure(list(x = c(6L, 5L, 1L), y = c(7L, 4L, 3L), z = c(1L, 
2L, 2L), column_indices = structure(c(1L, 3L, 2L), .Label = c("1,2", 
"1,3", "3"), class = "factor")), class = "data.frame", row.names = c(NA, -3L))

One solution involving dplyr and tidyr could be:

df %>%
 pivot_longer(-column_indices) %>%
 group_by(column_indices) %>%
 mutate(values = toString(value[1:n() %in% unlist(strsplit(column_indices, ","))])) %>%
 pivot_wider(names_from = "name", values_from = "value")

  column_indices values     x     y     z
  <chr>          <chr>  <int> <int> <int>
1 1,2            6, 7       6     7     1
2 3              2          5     4     2
3 1,3            1, 2       1     3     2
Related