browndynamite
browndynamite

Reputation: 133

Print Specific Output from multiple functions in R

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)
}
}

Upvotes: 0

Views: 495

Answers (2)

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

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)

Upvotes: 1

Brandon Bertelsen
Brandon Bertelsen

Reputation: 44638

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.

Upvotes: 1

Related Questions