[R] how to convert factors to numbers
Duncan Murdoch
murdoch at stats.uwo.ca
Sun Dec 14 19:47:38 CET 2008
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 price,
> high price, low price, closing price, volume and adjusted price (i.e.,
> adjusted for dividends and splits). I want to read and manipulate the data
> 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:
>
>> spy<-read.table("c:\\StockData\\SPY.txt")
>> attach(spy)
>> names(spy)<-c("QDate","OpenP","HighP","LowP","CloseP","Vol","AdjP")
>> spy[1,]
> 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
>> ChangeFromOpen<-spy[1,5]-spy[1,2]
> 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 price
> and the opening price, (much less compute averages, etc). This is clearly a
> "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.
More information about the R-help
mailing list