[R] Pass Conditional & loop argument into a function

David Winsemius dwinsemius at comcast.net
Thu Aug 9 20:27:24 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

I had another idea that would not go the route of parsing an expression:

 > rowSums(a^col(a))
[1] 1368 1779 2264 2829 3480

Does not need to re-specify the number of rows. And if you wanted to  
multiply each polynomial term with by a column-level constant vector,  
it would just be:

    rowSums( rep( const, each=nrow(a) )*a^col(a) )

E.G:

 > a^col(a)
      [,1] [,2] [,3]
[1,]    1   36 1331
[2,]    2   49 1728
[3,]    3   64 2197
[4,]    4   81 2744
[5,]    5  100 3375
 > const <- c(10, 1, 0.1)
 > rowSums( rep( const, each=nrow(a) )*a^col(a) )
[1] 179.1 241.8 313.7 395.4 487.5


>
>
> 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?

Doesn't work means .... what?

First you should tell us what is supposed to be accomplished. Is the  
"constant" just being added to a vector? Seems like you are going  
through incredibly complex efforts to do just this:

 > 1:5 + 5
[1]  6  7  8  9 10

-- 
David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list