I´m quite new at programming, and I started with R. I wanted to make a script which takes as input a matrix with the columns: time, x, y (coordenates) and then divide the time spent in each quadrant of a circular area. I have a roughly done script, but for any reason I don´t understand, when I execute the for loop in the editor, it appears all the letters red in the console with a "+" at the beginning of each line, which doesn´t let me open any other object any more when I call it.
set.seed(20)
x = matrix(rnorm(10,3,4),10,1)
y = matrix (rnorm(10,3,4),10,1)
time = matrix (1:10,10,1)
a = cbind (time,x,y)
colnames(a) = c("time","x","y")
upperright = a[,2] > 0 && a[,3] > 0
upperleft = a[,2] < 0 && a[,3] > 0
lowerright = a[,2] > 0 && a[,3] < 0
lowerleft = a[,2] < 0 && a[,3] < 0
calculation <- function () {
upperrightquadrant = 0
upperleftquadrant = 0
lowerrightquadrant = 0
lowerleftquadrant = 0
for (i in c(1:nrow(a))){
if (upperright) upperrightquadrant <<- sum((a[i,1]-a[i-1,1]))
if (upperleft)upperleftquadrant <<- sum((a[i,1]-a[i-1,1]))
if (lowerright) lowerrightquadrant <<-sum((a[i,1]-a[i-1,1]))
if (lowerleft) lowerleftquadrant <<- sum((a[i,1]-a[i-1,1]))
}}
output = lapply (a, calculation)
Best Solution
The
+
symbols are only a way to show that the current statement is conitnuation of the previous lines's statement. That's perfectly OK. There are a couple of other problems with your program which are stopping it from producing your intended result. If I have in fact, understood what you are trying to do, I have added a possible solution at the end. First, let me suggest the edits and the reason for them:&
should have been used instead of&&
.&
is the vectorized operator. So,upperright = a[,2] > 0 & a[,3] > 0
instead ofupperright = a[,2] > 0 && a[,3] > 0
.calculation <- function (a)
instead ofcalculation <- function ()
.if (upperright[i])
instead ofif (upperright)
.sum((a[i,1]-a[i-1,1]))
at i==1, i-1 equals 0. If you are only counting, incrementing the count by 1 should be sufficient.<<-
.Finally, as you have already written the
for
loop to iterate over your matrix rowwise, no need for lapply or other similar looping functions.Only a suggestion: Use
<-
operator for assignments instead of=
.Now, the corrected program:
EDIT
This is the edit for what you requested (Case where time instances are not contiguous). Just replace the
for
loop with this one:Hope, this helps.