bruce01
bruce01

Reputation: 93

Return value from function when iterating in a loop R

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.

Upvotes: 2

Views: 29972

Answers (1)

Karl Forner
Karl Forner

Reputation: 4414

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
}

Upvotes: 4

Related Questions