[R] basic information defining functions

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Tue Nov 25 12:20:25 CET 2008


> i am looking from some insights to define own R functions. so far i 
> found most basics in documentations that are around on the web. except 
> for one thing:
> 
> I´d like to define some function, say:
> 
> #assume my data matrix contains vectors like data$myColumn1,data 
> $myColumn2 etc.

Do you really mean data matrix, or do you mean data frame?

> getMyColumn <- function (columnid){
> 
> x<-data$MyColumn?columnid?[data$indexone=1 & data$index2=5]
> 
> return(x)
> 
> }

It's not terribly clear what you want to do with this function.  Question 
marks don't mean anything in the middle of a statement, so I don't know 
what 
data$MyColumn?columnid?[data$indexone=1 & data$index2=5] 
is supposed to do.

Also, you don't need the return keyword - the last line of a function is 
the return value.

> Do I need to use assign or eval first ? I tried to use paste to 
> combine something like: paste("data$MyColumn",columnid,sep="") which 
> did not work.

paste returns a string, not a variable.  You can evaluate the contents of 
the string using 
eval(parse(text=paste("data$MyColumn",columnid,sep="")))
This is however a method of last resort; there is almost always a better 
way to do things than using eval.
 
> I am happy to get any help with the problem, but also thankful for 
> some useful link or guide on how to define own functions properly, 
> especially the dynamic naming and return part

You probably don't need to bother with dynamic naming, but take a look at 
FAW on R, q7.21.

Regards,
Richie.

Mathematical Sciences Unit
HSL

------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}



More information about the R-help mailing list