[R] Using for (i in ...) command with function
Prof Brian Ripley
ripley at stats.ox.ac.uk
Thu Jun 17 01:14:42 CEST 2004
Might this be the issue:
> for(i in 1:10) {i}
>
? Note, no output. If you want to print the result of final(data, i) ina
for() loop you need to do so explicitly.
A second issue is that your example code defines sum() in terms of sum()
and so is recursive. You should get the error message
Error in sum(data[, x]) : evaluation nested too deeply: infinite recursion
/ options(expression=)?
At least I do with your code below.
On Wed, 16 Jun 2004, Jennifer Emond wrote:
> Hi,
>
> I have defined a function, and I want to apply this function for
> different values of i, yet, when I use a for command, it only
> executes the function for the first value of i.
>
> My functions are long, but here is an example. The problem is if I run
> the following code:
>
> tab<-function(data,x){
> a.length<-length(data[,x])
> return(a.length)
> }
>
> sum<-function(data,x){
> b.sum<-sum(data[,x])
> return(b.sum)
> }
>
> final <- function(data,c){
> if(is.factor(data[,x])==TRUE){
> tab(data,x)
> } else{
> sum(data,c)}
> }
>
>
> Then try to run:
> for (i in 1:10){
> final(data,i)
> }
>
> I get only the output for function for when i=1, and not for each value.
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list