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.


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



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

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



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

Need Your Help

Formatting DateTime to be Human Readable (Eg Messaging App)

windows-phone-7 xaml silverlight-4.0 windows-phone-7.1

How can I format a DateTime binding to look exactly (or as similar as possible) like the Messaging Hub.

Fancytree remove blue border when selected

javascript css fancytree

Using fancytree, how can I prevent the boundary around the fancytree div from becoming blue when it's active?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.