[R] Help with Function!
Paul Johnson
pauljohn32 at gmail.com
Sat Mar 14 00:58:26 CET 2009
On Fri, Mar 13, 2009 at 6:28 PM, Lars Bishop <lars52r at gmail.com> wrote:
> Dear All,
>
> I need to write 'n' functions on 'm' variables. The functions should be
> constructed according to the values of an (nxm) matrix of '1/0' values as
> follows. For example,
>
> if row1 is equal to ,say [1 0 .......0 0] then f1 <- (1+x1)
> if row 2 is equal to, say [1 1 1 0...0 1] then f2
> <-(1+x1)*(1+x2)*(1+x3)*(1+xm)
> if row n is equal to [0 1 0 1 1 0 ..... 0] then fn <-(1+x2)*(1+x4)*(1+x5)
>
> Is there an efficient way to write these functions? Note that each f(x) is a
> function of m variables, independently on whether the function explicitly
> includes a given variable or not.
>
> Many thanks for your help!
>
> Regards,
indic <- matrix(c(1,1,0,0,0,1,0,0,1,0), ncol=5)
X <- data.frame(x1=3,x2=3,x3=4,x4=5,x5=6)
### Give this function 2 vectors, an "indicator
### vector ind and a value vector Xin
myHomework <- function(ind, Xin){
prod(Xin[ , which(ind==1)])
}
myHomework(indic[1,], X[1,])
myHomework(indic[2,], X[1,])
Seems to give the right answer. Let me know if we get an A.
PJ
--
Paul E. Johnson
Professor, Political Science
1541 Lilac Lane, Room 504
University of Kansas
More information about the R-help
mailing list