[R] Pass Conditional & loop argument into a function

David Winsemius dwinsemius at comcast.net
Thu Aug 9 05:19:02 CEST 2012


On Aug 8, 2012, at 2:16 PM, greatest.possible.newbie wrote:

> 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

You want to evaluate that object which is not yet an expression. The  
parse function will turn it into an expression and then eval will work:

 > eval( parse(text=b) )
[1] 1368 1779 2264 2829 3480

Here's another approach:

 > colnames(a) <- c("alin", "asqr", "acube")
 > adat <- as.data.frame(a)
 > with( adat, alin+asqr^2+acube^3)
[1] 1368 1779 2264 2829 3480

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

David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list