2

I have stayed away from functions in R but decided it is better practice. Now I have this issue. I write my function:

 myFunction<-function(tab){ #takes tabular input
     inP<-c()
     for (x in 1:dim(tab)[1]){ #iterate over rows
         rname<-rownames(tab)[x] #rownames as output
         if(rname<5) inP<-c(inP,rname) #trivial work
     }
     return(inP) #return the vector made above
 }

 tablist<-as.list(paste("tab",1:4,sep=""))
 for (x in 1:length(tablist)){
     tablist[[x]]<-table(c(1:10),c(1:10))
 }

 inPvec<-c() #predefine vector to concatenate results into
 for (x in 1:length(tablist)){ #tabs holds multiple tables as a list
      myFunction(tablist[[x]]) #run myFunction for each table held in tabs
      inPvec<-c(inPvec,inP) #concatenate results from each iteration
 }

 inP
 #NULL

 myFunction(tablist[[1]])
 #[1] "1" "2" "3" "4" "10"

Edited as workable example: apologies for laziness.

If you run for the loop in the example, inP returns NULL, as does inPvec. Bu running single tables in the function return the correct value. However, inP is NULL on calling it, so I guess this is where my issue is.

I want everything from the loop iterating over the function to be returned to a single vector eg:

 inPVec
 #[1] "1" "2" "3" "4" "10" "1" "2" "3" "4" "10" "1" "2" "3" "4" "10" etc

Any help much appreciated.

bruce01
  • 93
  • 1
  • 4
  • 11
  • Please help us help you by providing us with a reproducible example (i.e. code and example data), see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for details. – Paul Hiemstra Aug 22 '13 at 09:03
  • Sorry, edited now to run as standalone example. – bruce01 Aug 22 '13 at 09:53

1 Answers1

4

The problem is that you do not get the result of your function:

inPvec<-c() #predefine vector to concatenate results into
for (x in tabs){ #tabs holds multiple tables as a list
     inPvec<-c(inPvec,myFunction(x)) #concatenate results from each iteration
}

and you should correct your function too:

myFunction<-function(tab){ #takes tabular input
    inP <- c()
    for (x in 1:dim(tab)[1]){ #iterate over rows
        rname<-rownames(tab)[x] #rownames as output
        if(rname=="something") inP<-c(inP,rname) #trivial work
    }
return(inP) #return the vector made above
}
Karl Forner
  • 4,175
  • 25
  • 32