vendredi 5 août 2016

R ifelse more than command in the true section

I am new to R. I've looked for an answer to my question, but failed to find anything that works for me.

I have the following data.table:

data2 <- fread("file.txt", header = T, sep= "|", quote = "^" stringsAsFactors=FALSE);

Accounts_filed_date Incorporation_Date 
         2015-08-25         1863-05-01   
         2016-06-28         1863-07-16    
         2016-06-29         1863-12-29  
         2015-12-10         1880-08-17

Y <- function(incorporation_date, accounts_filled_date)
{timee <-Sys.Date()-incorporation_date;timee <- as.numeric(timee);
  if(timee/365 <2){y=0; return(y)}
  else{x <- as.Date(format(accounts_filled_date, "%2016-%m-%d"));
   + x <- Sys.Date()- x;
   + x <- as.numeric(x);
   + if(x<274) {y <-timee/365; return(pmax(pmin(y,5),0))}
   + else{y<-timee/365-1; return(pmax(pmin(y,5),0))}}}

data2[, c("Y") := Y(Incorporation_Date, Accounts_filed_date), with = FALSE]

However, that doesn't work because incorporation_date and accounts_filled_date are vectors.

I've tried ifelse but with the following code:

Y <- function(incorporation_date, accounts_filled_date) 
{timee <- Sys.Date()-incorporation_date;timee <- as.numeric(timee); 
timee<- timee/365;
ifelse(timee<2,y=0,
       x<-as.Date(format(accounts_filled_date, "%2016-%m-%d"));
       x <-Sys.Date()- x;
       x <- as.numeric(x);
       ifelse(x<274,y <-timee, y<- timee-1));
return(pmax(pmin(y,5),0))} 

which returns the following:

Error: unexpected ';' in "Y <- function(incorporation_date, accounts_filled_date) {timee <- Sys.Date()-incorporation_date;timee <- as.numeric(timee); timee <- timee/365;ifelse(timee<2,y=0,x

Basically, my question is: How can I include more than one action in the 'false' part of the ifelse statement?

Aucun commentaire:

Enregistrer un commentaire