[R] Pass Conditional & loop argument into a function

S Ellison S.Ellison at LGCGroup.com
Thu Aug 9 03:22:25 CEST 2012


Why do you want to do this via character strings at all? 
You have at least two alternatives. First, you can pass the exponents as a vector and the data as a matrix and then just do the calculation:

f <- function(mat, expon) {
       apply(mat, 1, function(x, e) sum(x^e), e=expon)
                        #this relies on the vectorised nature of R and particularly operators like ^
}

f(a, 1:3)
# [1] 1368 1779 2264 2829 3480

Alternatively, pass a function to your function:

f2 <- function(mat, fun, ...) {
        apply(mat, 1, fun, ...)
}
f.to.pass <- function(x, e) sum(x^e)

f2(a, f.to.pass, e=1:3)
# [1] 1368 1779 2264 2829 3480


________________________________________
From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of greatest.possible.newbie [daniel.hoop at gmx.net]
Sent: 08 August 2012 22:16
To: r-help at r-project.org
Subject: Re: [R] Pass Conditional & loop argument into a function

Ok I see that point with the quotes. But what I want to do still doesn't
work:

a <- matrix(1:15,ncol=3)
b <- paste(  paste("a[," ,paste(1:3), "]",sep="")
,"^",1:3,sep="",collapse="+")
b
#[1] "a[,1]^1+a[,2]^2+a[,3]^3"
#instead of (which I want)
a[,1]^1+a[,2]^2+a[,3]^3
#[1] 1368 1779 2264 2829 3480


or I want to change some function input (dramatically) just by changing two
conditional arguments (in my case constant and c).
a <- matrix(1:15,ncol=3)
b <- matrix(NA,nrow=nrow(a),ncol=ncol(a))
constant <- 1
c <- 5

for (j in 1:ncol(a))
  b[,j] <- mapply(function(x){
  if(is.null(constant))  {paste(paste("x^", paste(1:c) , sep="", collapse="
+ ") , ", a[,",j,"]" ,sep=" ")
  } else if(!is.null(constant)) {paste(paste(constant, paste("x^",
paste(1:c) , sep="",collapse="+"),collapse="+") , ", a[,",j,"]" ,sep=" ") }
  })

By the way.. Can anyone tell my why collapse doesn't work in outer paste
function?



--
View this message in context: http://r.789695.n4.nabble.com/Pass-Conditional-loop-argument-into-a-function-tp4639580p4639681.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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.

*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list