[R] how to convert factors to numbers
ggrothendieck at gmail.com
Sun Dec 14 20:15:52 CET 2008
Also you might want to use read.zoo from the zoo package
which will read the file in and will convert the dates at the same time
into a zoo object. Something like:
z <- read.zoo("myfile.csv", header = TRUE, sep = ",", format = "%m/%d/%Y")
Or rather than creating files you may wish to use
the quantmod package which has facilities for directly
reading such data from the web.
On Sun, Dec 14, 2008 at 1:47 PM, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> On 14/12/2008 12:38 PM, doloop wrote:
>> Hello, I am relatively new to using R. I am using R version 2.8.0. I
>> have a
>> program that downloads stock data from Yahoo! Finance and stores it to a
>> text file on my hard drive. The text file contains the date, opening
>> high price, low price, closing price, volume and adjusted price (i.e.,
>> adjusted for dividends and splits). I want to read and manipulate the
>> in R. However, when I use read.table, it treats all of the data as
>> "factors" and I do not know how to treat the data as numbers:
>> QDate OpenP HighP LowP CloseP Vol AdjP
>> 1 12/14/2006, 141.86, 143.24, 141.84, 143.12, 64755200, 138.34
> Notice the commas: they are being read as part of the data, not as
> separators. I imagine you need to use read.csv, not read.table, or specify
> sep="," to the latter.
> Once you're reading the data properly, you can convert to a number using
> as.numeric(as.character( f )), where f is the factor. Don't just use
> as.numeric(f); that will just extract the internal encoding.
> Duncan Murdoch
>> Warning message:
>> In Ops.factor(spy[1, 5], spy[1, 2]) : - not meaningful for factors
>> As you can see, I cannot calculate the difference between the closing
>> and the opening price, (much less compute averages, etc). This is clearly
>> "newbie" problem. In my defense, I am using the book by Michael Crawley
>> (The R Book) as my teaching guide, but I cannot find the answer to this
>> question in that rather densely packed book.
>> Any help is appreciated.
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help