[R] If loops?
David Winsemius
dwinsemius at comcast.net
Fri Nov 2 03:02:28 CET 2012
On Nov 1, 2012, at 6:38 PM, arun wrote:
> Hi,
>
> You can try this also :
> set.seed(132)
> dat1<-data.frame(Company=rep(LETTERS[1:4],c(3,4,5,6)),Last_year=sample(2005:2012,18,replace=TRUE))
> dat2<-dat1[order(dat1$Company,dat1$Last_year),]
> dat2$Last<-ave(dat2$Last_year,dat2$Company,FUN=function(x) ifelse(x>=2009,2009,x))
None of the `ifelse` conditional or desired consequent depend on the Company value. Just wasted CPU cycles are the result. If you choose to use `ifelse` , then why not:
dat2$Last2<- ifelse(dat2$Last_year > 2009, 2009, dat2$Last_year) # the '=' also not needed
head(dat2)
>
> # Company Last_year Last
> #3 A 2007 2007
> #1 A 2010 2009
> #2 A 2012 2009
> #6 B 2007 2007
> #4 B 2008 2008
> #5 B 2008 2008
>
> identical(dat2[,3],pmin(dat2[,2],2009))
> #[1] TRUE
>
> identical(dat2[,4],pmin(dat2[,2],2009))
[1] TRUE
> A.K.
>
>
>
> ----- Original Message -----
> From: kebrab67 <selamgetachew at gmail.com>
> To: r-help at r-project.org
> Cc:
> Sent: Thursday, November 1, 2012 8:41 PM
> Subject: [R] If loops?
>
> I have a set of data with 205 988 observation sand 10 variables , three of
> which are Legal_status, Date_of_incorporation and Last_year. I set my time
> horizon from 1989 to 2009. Now I want to know when a company is dead. If
> Last_year is bigger or equal to 2009 then I say that a new "variable" last
> is 2009. If Last_year is smaller than 2009 then my new variable "last" is
> equal to the variable "Last_year". I wanted to know how I can generate this
> new variable and connect it to my original data called data.
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/If-loops-tp4648199.html
> Sent from the R help mailing list archive at Nabble.com.
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
David Winsemius, MD
Alameda, CA, USA
More information about the R-help
mailing list