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.

2
  • Please help us help you by providing us with a reproducible example (i.e. code and example data), see stackoverflow.com/questions/5963269/… for details. Commented Aug 22, 2013 at 9:03
  • Sorry, edited now to run as standalone example. Commented Aug 22, 2013 at 9:53

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, sorry again, inP was meant to be defined inside the function.
Great, thanks Karl, I understand: the return value is myFunction(x), as opposed to the value defined and returned in myFunction (eg inP).
what an "interesting" / different syntax R uses for concatenation. Glad to have stumbled onto this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.