John John - 1 year ago 67
R Question

Reading a text file in R

I've always read in text files in R ok without any problems. I have just noticed today that when reading a text file in RStudio, it automatically imports the variables as factors. This is easily fixed with

stringsasFactors = F
but then it now imports every column as a character. I'm using read.table for this as in:

read.table("file.text", stringsAsFactors = F, header = T)

Anybody know how to get the
command to import text file columns as numeric? I've searched around a bit but it would be useful to know if anybody else is having the same issues with

Answer Source

You can specify a vector which contains the classes of the columns which you intend to read. For example, if your source data had two columns, the first which you wanted as numeric, and the second as factor, then you coul use this:

classes <- c(col1="numeric", col2="factor")
read.table("file.text", colClasses=classes, stringsAsFactors=FALSE)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download