ruben baetens
ruben baetens

Reputation: 2926

Read data in form '1.4523e-9'

I'm trying to read data from a *.txt or *.csv file into R with read.table or read.csv. However, my data is written as e.g. 1.4523e-9 in the file denoting 1.4523*10^{-9} though ggplot recognizes this as a string instead of a real. Is there some sort of eval( )-function to convert this to its correct value ?

Upvotes: 0

Views: 47

Answers (1)

Joe
Joe

Reputation: 3991

Depending on the exact format of the csv file you import,read.csv and read.table often simply convert all columns to factors. Since a straightforward conversion to numeric as failed, I assume this is your problem. You can change this using the colClasses argument as such:

# if every column should be numeric:
df <- read.csv("foobar.csv", colClasses = "numeric")

#if only some columns should be numeric, use a vector.
#to read the first as factor and the second as numeric:
read.csv("foobar.csv", colClasses = c("factor", "numeric")

Of course, both of the above are barebones examples; you probably want to supply other arguments as well, eg header = T.

If you don't want to supply the classes of each column when you read the table (maybe you don't know them yet!), you can convert after the fact using either of the following:

df$a <- as.numeric(as.character(a)) #as you already discovered
df$a <- as.numeric(levels(df$a)[df$a])

Yes, these are both clunky, but they are standard and frequently recommended.

Upvotes: 1

Related Questions