[R] formula in function as text?

Petr PIKAL petr.pikal at precheza.cz
Tue Jan 17 15:32:35 CET 2012


Hi
> 
> Hello all,
> 
> It might be a simple question, but I cannot find the solution, as I do 
not
> know which subjects I should search on. So, much thanks for he/she we 
can
> help me.
> I am creating a function and would like to place a formula in the 
function,
> without it being executed immediately. Like saving it temporary as 
'text'.
> 
> Simplified version of what I would like to be able to do:
> 
> test<-function(a,x){
> if(a<5){ b<-3+ x[i]}

What is i?

> if(a>5){ b<- 6 + x[i]}
> y<-1:10
> for (i in 1:10){y[i]<-4 + b}
> return(y)
> }
> 
> In my perfect world, R will replace b in the formula y=4+b by the
> appropriate b, indicated by the condition (value of a).

If you want perfect R world you shall us R approach.

Let's suppose you have vector "a" with values below and above 5. and 
vector "x" which you want to use for computing "b"

set.seed(111)
a <-sample(1:10, 10)
x <-runif(10)

you can compute vector "b" according to your condition

b <- (((a>5)+1)*3) + x
# I included number 5 to computing 3

and based on this you can compute y

y <- 4+b

You can put it in a function if you want.

test<-function(a,x) {
b <- (((a>5)+1)*3) + x
y <- 4+b
return(y)
}

Regards
Petr


> It now takes for 'b' only the first argument of x (+3 or 6). I know I 
can
> solve the problem by also looping over b and turning it into a vector, 
but
> I would like to know if it is also possible in the way stated above. If 
I
> put 3+x[i] in "" to make it a character, it will still be character at
> y<-4+b or when I use as.numeric, it will create NA....
> 
> Thanks in advance,
> 
> Julia
> 
>    [[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.



More information about the R-help mailing list