I am starting to learn R and I got an error for the loop.
Here is the error I got:
Error in names(data1)[5] <- "TR" :
'names' attribute [5] must be the same length as the vector [4]
Here is my code:
#read data
data1<-read.table("C_0.txt",header = T,sep=",")
#name the 5th col TR
names(data1)[5]<-"TR"
#calculate the length of data1
n<-nrow(data1)
#initialize first TR value to NA
data1[1,5]<-NA
for (i in 1:(n-1)){
if (data1[i,3]==data1[i+1,3]) {data1[i+1,5]<-data1[i,5]}
if (data1[i,3]< data1[i+1,3]) {data1[i+1,5]<- 1}
if(data1[i,3]> data1[i+1,3]) {data1[i+1,5]<- -1}
}
Here is the algorithm I am trying to codify: if the current price is above the previous price, mark +1 in the column named TR if the current price is below the previous price, mark -1 in the column named TR if the current price is the same as the previous price, mark the same thing as in the previous price in the column named TR
I marked the first TR row as NA because there is no price to compare it to.
here is the data from C_0.txt:
Date,Time,Price,Size
02/18/2014,05:06:13,49.6,200
02/18/2014,05:06:13,49.6,200
02/18/2014,05:06:13,49.6,200
02/18/2014,05:06:14,49.6,200
02/18/2014,05:06:14,49.6,193
02/18/2014,05:44:41,49.62,100
02/18/2014,06:26:36,49.52,100
02/18/2014,06:26:36,49.52,500
02/18/2014,07:09:29,49.6,100
02/18/2014,07:56:40,49.56,300
02/18/2014,07:56:40,49.55,400
02/18/2014,07:56:41,49.54,200
02/18/2014,07:56:43,49.55,100
02/18/2014,07:56:43,49.55,100
02/18/2014,07:56:50,49.55,100
02/18/2014,07:57:12,49.53,100
02/18/2014,07:57:12,49.51,2200
02/18/2014,07:57:12,49.51,100
02/18/2014,07:57:12,49.5,200
Thanks a lot!