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

Frank S. f_j_rod at hotmail.com
Mon Sep 29 21:17:12 CEST 2014


Hi to all members of R list,

 

I’m working with data.table package, and with 6
variables: "ID" (Identifier), "born" (Birthdate), "start" (Starting date), "register" (date of measurement), "value"and "end" (date of expiration). So, the natural order of dates 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:1. First: 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).Afterwords:2. Remove only
specific rows (not all ID) where “register” is previous to “start”.3.Remove only
specific rows (not all ID) where “end” is previous to “register”.

I have: 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] BUT I GET AN ERROR MESSAGE: Error: syntax error, unexpected ELSE in "else"  Please, can anyone help me? Thank you!!  

 		 	   		  
	[[alternative HTML version deleted]]



More information about the R-help mailing list