I am using RStudio and I am using the following R Codes to import a file into R. I need to exclude one specific column called "Approach".

Currently, my R codes to read the file stand as follows:

df1 <- read.csv("myfile.csv", check.names=FALSE, header = TRUE, fileEncoding="latin1")

I have tried something like this but it is not working:

excl_Approach_Col<-c("Approach")
df1 <- read.csv("myfile.csv", check.names=FALSE, header = TRUE, col.names!= excl_Approach_Col, fileEncoding="latin1")

I am getting the following error message:

Error in read.table(file = file, header = header, sep = sep, quote = quote,
: object 'col.names' not found

I know I can import the full file as df1 and then proceed to drop that specific column. However, it would be nice if I could exclude the column during the read file step.

Is this possible? Do I need any specific package to perform this operation?

2 Answers

2
MatthewR On Best Solutions

You can use 'fread' in 'data.table' for loading select columns. 'select' allows you to pick columns, 'drop' allows you to exclude:

library( data.table)
a <- data.table::fread( 
     "myfile.csv"  ,  
    drop = "Approach"
)   
0
Hunaidkhan On

you can use to import only certain columns

read.csv(file = "result1", sep = " ")[ ,1:2]

or if the columns names are known

read.csv(file = "result1", sep = " ")[ ,c('col1', 'col2')]