# R Selecting columns of a data frame based on a vector

I have an example data frame as shown below.

> x=data.frame(id=1:5,c1=letters[1:5],c2=letters[13:17]) > x id c1 c2 1 1 a m 2 2 b n 3 3 c o 4 4 d p 5 5 e q

I want to create a vector out of this data frame which selects a different column for each row based on another vector. So if that vector is

> vars [1] 1 2 2 1 1 >

I want for the 1st row in x, column 1, for the second row in x, column 2 and so on. So the expected output vector (or data frame) would be if vector

a n o d e

if data frame

id V1 1 a 2 n 3 o 4 d 5 e

Any help, much appreciated.

## Answers

You can 'slice' a data frame using a matrix:

y=data.frame(1:5,c(1,2,2,1,1)) x[2:3][as.matrix(y)]

result:

[1] "a" "n" "o" "d" "e"

Let's generalise this by creating a function

selector=function(x)matrix(c(seq_along(x),x),ncol=2)

Note that there is one column to be ignored at the start, so add 1 to your select vector v

v=c(1,2,2,1,1) x[selector(v+1)]

result

[1] "a" "n" "o" "d" "e"