[R] Odp: defining new variable

peter dalgaard pdalgd at gmail.com
Fri Jul 1 16:26:42 CEST 2011


On Jul 1, 2011, at 15:22 , Petr PIKAL wrote:

> Hi
> 
> r-help-bounces at r-project.org napsal dne 01.07.2011 14:32:31:
> 
>> B Marktplaats <gm.spam2011 at gmail.com> 
>> 
>> 
>> I'm new to R and I'm trying to define new quite simple variable but I'm
>> struggling with R syntax (when coming to dates) for a while and still
>> getting <errors>  on it.
>> 
>> I would be very grateful if someone could help me with this, to be able 
> to
>> move on.
>> 
>> I have the following variables:
>> 
>> - Transplant.date
>> - Faildate
>> - Death.date
>> 
>> The new variable Time should do the following thing:
>> 
>> Time <-
>> 
>> If Not IsNull(<Faildate>) Then DaysBetween(<transplant date> 
> ,<Faildate>)
>> Else If IsNull(<Faildate>) And Not IsNull(<Death date>) Then
>> DaysBetween(<transplant date> ,<Death date>) Else If IsNull(<Faildate>) 
> And
>> IsNull(<Death date>) Then DaysBetween(<transplant date> ,CurrentDate())
> 
> I bet there is more elegant solution but
> 
> with such data frame you can
> 
>> df
>          td         fd         dd
> 1 2011-06-11 2011-06-16       <NA>
> 2 2011-06-12       <NA> 2011-06-22
> 3 2011-06-13       <NA> 2011-06-23
> 4 2011-06-14       <NA> 2011-06-24
> 5 2011-06-15       <NA>       <NA>
> 
> df$days<-rowSums(sapply(df[,2:3], "-", df$td), na.rm=T)
> 
> Then you can check for NA values in fd and dd and change respective values 
> by 
> 
> df$days[rowSums(is.na(df[,2:3]))==2] <- 
> Sys.Date()-df$td[rowSums(is.na(df[,2:3]))==2]
> df
>          td         fd         dd days
> 1 2011-06-11 2011-06-16       <NA>    5
> 2 2011-06-12       <NA> 2011-06-22   10
> 3 2011-06-13       <NA> 2011-06-23   10
> 4 2011-06-14       <NA> 2011-06-24   10
> 5 2011-06-15       <NA>       <NA>   16
>> 

I'd go for something like

df <- within(df,{
 days <- Sys.Date() - td
 days[!is.na(dd)] <- (dd - td)[!is.na(dd)]
 days[!is.na(fd)] <- (fd - td)[!is.na(fd)]
})

-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list