Question

I have a dataset with 100 columns and it doesn't have a header.

I have an int vector that consists of some numbers ranges between 1 to 100. For example, a vector with "2 5 62 78".

Now when I read the dataset using read.table, all I want is to select column 2, 5, 62 and 78 from the dataset. How can I do that? Many thanks.

Was it helpful?

Solution

What you want is the option colClasses of read.table() (and the derivative functions). It allows you to pass a character vector with the classes of each column in the data. If you set that to "NULL" the column will be skipped. You can set the whole thing to "NULL" and then only change the ones you want to import (based on their class).

Proof of concept below.

cc <- rep('NULL', 100)       ## skip all 100 columns
cc[c(2, 5)] <- 'integer'     ## 2 and 5 are integer
cc[c(62, 58)] <- 'character' ## 62 and 58 will be imported as character
df <- read.csv('really-wide-data.csv', colClasses=cc)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top