0

I have multiple user defined functions written in R. I usually source the code and then print the output in R console. My problem is I have 3 function written in one file and all three functions have similar output( here I have z which is common in all three function).. Is there any solution in R where I do not have to type print(z) at the end of every function but after sourcing my code I should be able to print z specific to function?

harry<-function(i){
for(i in 3:5) {
    z <- i + 1
    print(z)
}
}
harry1<-function(i){
for(i in 1:5) {
    z <- i + 1
    print(z)
}
}

harry2<-function(i){
for(i in 1:5) {
    z <- i + 5
    print(z)
}
}
3
  • 2
    Use return instead. Commented Jan 28, 2014 at 18:59
  • I am not familar with R that much can you please explain in detail. Commented Jan 28, 2014 at 19:10
  • 1
    You should take some time to understand the intent of R's style. You'll be happier (and work faster) if you source regularly used functions once, keep them in your environment, and write either commands or a script to execute the functions. This is in addition to understanding the difference between print and Brandon's suggestion to use return. Commented Jan 28, 2014 at 19:15

2 Answers 2

1
harry <- function(i){
z <- 1 # initialize
  for(i in 3:5) {
    z[i] <- i + 1 # save to vector
  }
return(z) # returns the object z
}

Now you can go:

harry(100)
z <- harry(100)
print(z)    
z

To access the same information.

Sign up to request clarification or add additional context in comments.

Comments

1

Might I suggest a more general way of doing things?

harry<-function(i,sq){
   sapply(sq, function(s,i) {
      s + i
   }, i=i )
}
harry(i=1,sq=3:5)
harry(i=1,sq=1:5)
harry(i=5,sq=1:5)

4 Comments

My purpose here is I have 16 different functions but all has similar variables to print. I want to reduce the length of my Code by not typing similar printing statement at the end of every function
There is great not-getting-it in this one, Obi-Wan.
@user35571 Right. Pass in the variables you want to print each time, or whatever differs. Put some thought into generalizing it rather than writing separate functions that embed your data.
There is no way I can generalize those function but still have the similar output .. Any way I was expecting some good help here...

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.