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.
You can ‘slice’ a data frame using a matrix:
result:
Let’s generalise this by creating a function
Note that there is one column to be ignored at the start, so add 1 to your select vector v
result