[R] Loop does not work: Error in else statement (II)

Frank S. f_j_rod at hotmail.com
Tue Sep 30 14:54:53 CEST 2014


 

Hi to all members of R list,

 

I’m working with data.table package, and with 6
variables:

 

ID: Subject identifier

born: Birthdate

start: Starting date 

register: date of measurement 

value: Value of measurement

end: date of expiration of the measurements.

 

So, the natural order of date variables would be: born
=< start =< register =< end. As an example, I have:

 

DT <- data.table(ID =
as.factor(rep(1:4,each=2)), 

      born=as.Date(rep(c("1955-02-20","1990-07-25","1972-03-18",
"1988-05-03"),each=2)),

      start=as.Date(rep(c("1953-03-28","1990-07-01","1983-09-05","1988-07-18"),each=2)),

      register = as.Date(c("1955-08-11",
"1958-03-28", "1990-07-09", "1992-07-01", 

                  "1983-09-05", "2002-09-28",
"1992-07-10", "1993-03-12")),

      value=c(205, 346, 34, 76, 320, 148, 209, 274),

      end=as.Date(rep(c("1960-11-05",
"1997-10-15", "2002-09-27",
"1997-03-02"),each=2)))

 

I would want to make 3 operations:

a)      Remove
entire ID’s where start is previous to born date (excepting those subjects
whose month and year values are the same in “start” and “born” variables: I
assign “born” date to “start” date in these cases).

b)      Remove
only specific rows (not all ID) where “register” is previous to “start”.

c)       Remove
only specific rows (not all ID) where “end” is previous to “register”.

 

DT[ , 

  {


   
if (all(born > start))  

   
{

   
indx <- which(paste(year(born))==paste(year(start)) &  paste(month(born))==paste(month(start))) 

   
result <- list(born=born[indx],start=born[indx],register=register[indx],

value=value[indx], end=end[indx]) 

   
}  

     
if (all(register > start) | all(end > register))

      {

     
      indx <- which((register
> start) | (end > register))

     
      result <-
list(born=born[indx],start=start[indx], register=register[indx], 

value=value[indx], end=end[indx]) 

}

      else

      {

      
     NULL

     
      }

  else

   
{

   
indx <- which(all(register > start) | all(end > register))

   
result <- list(born=born[indx], start=start[indx],
register=register[indx], 

value=value[indx], end=end[indx]) 

    
}

  
result

  
}, by=ID]

 

Error: unexpected 'else' in:

"      }

  else"

 

 		 	   		  
	[[alternative HTML version deleted]]



More information about the R-help mailing list