Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting non-consecutive columns in R tables

Tags:

r

Let's say I have a some table, T. Assume T has 5 columns. I understand how to select any consecutive subset of columns and store them as a new table. For that I would use brackets and a colon to the right of a comma:

newT <- T[,2:4]   # creates newT from columns 2 through 4 in T 

But how do I select non-consecutive columns for subsetting? Let's say I want to select Column 1 and Column 3? How do I go about doing this? Another type of selection I may want to do, and not sure how to, is selecting random columns from T.

like image 845
user938301 Avatar asked Nov 17 '11 21:11

user938301


1 Answers

You simply first generate the indexes you want. The c function allows you to concatenate values. The values can be either column indices or column names (but not mixed).

df <- data.frame(matrix(runif(100), 10)) cols <- c(1, 4:8, 10) df[,cols] 

You can also select which column indices to remove by specifying a negative index:

df[, -c(3, 5)] # all but the third and fifth columns 
like image 152
Tommy Avatar answered Sep 20 '22 15:09

Tommy