Here's one way :
ds <- data.frame( st = runif(100), s0=runif(100),
s1=runif(100),s2=runif(100),mp=runif(100))
ds <- within( ds, {
n1 <- 1*( st>0.38 )
n2 <- numeric( length( st ) )
n2[ is.na(st) | st <= 0.38 ] <- .25
n2[ s0 == mp ] <- .25
n2[ s2 == mp ] <- .5
n2[ mp == 1 ] <- .75
} )
See ?within for why/how this works.
Romain
On 01/14/2010 11:10 AM, Olivier Deckmyn wrote:
Dear all,
I'm learning R, with a "classical" programming background. Some hours were
necessary for me to programm the "vector" way.
Here is my dataset :
ds<- data.frame( st=runif(100), st=runif(100),s1=runif(100),mp=runif(100))
I need to generate 2 new variables. First was easy :
ds$n1<- (ds$st>0.38)*1
Second involve a "if" statement.
Here is the "python way" of expressing what I need :
nash<- function(st,s0,s1,mp){
if (is.na(st) | (st<=0.38)){
return(0.25)
}
if (s0 == mp){
return(0.25)
}
if (s1 == mp){
return(0.5)
}
if (mp == 1){
return(0.75)
}
}
I would like to do something like :
ds$n2<- nash(ds)
I mean I would like to add a new variable "n2", whose value depends on the
value of other variables - row per row.
I played with a for loop (don't flame :p), with apply functions and
derivatives, with a logical set, etc....
Can you help me find the "R" way, please ?
Cheers,
--
Olivier Deckmyn | oliv...@deckmyn.org | 06 73 40 89 88
--
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/KfKn : Rcpp 0.7.2
|- http://tr.im/JOlc : External pointers with Rcpp
`- http://tr.im/JFqa : R Journal, Volume 1/2, December 2009
______________________________________________
R-help@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.