How can I specify which columns to select using read.table in R

蓝咒 提交于 2019-12-02 19:14:55

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/23242812/how-can-i-specify-which-columns-to-select-using-read-table-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!