Search code examples
rfunctionreturnlabel

Labels for my solutions with R programming function command


Just learning R-programming and am trying to find a way to include a description with the solutions I get from my function. For example, if i solve for Area, I want the function to say "Area = 2", rather than just "2". I've tried the print/paste command, but for the life of me all the different variations I tried wont work with the function command. Perhaps I'm missing something simple?

    TrapGeo<-function(b,m,y){ 
A=((b+m*y)/y)
#Flow Area
P=(b+2*y*(sqrt(1+(m^2))))
#Wetted Perimeter
R=A/P
#Hydraulic Radius
B=b+2*m*y
#Top Water Width
D=A/B
#Hydraulic Depth
output=c(A, P, R, B, D)
return(output) 
print(paste("Flow Area =", A)) 
print(paste("Wetted Perimeter =", P)) 
print(paste("Hydraulic Radius =", R)) 
print(paste("Top Water Width =", B)) 
print(paste("Hydraulic Depth =", D)) 
}

As of right now, the function returns only the output as I have asked it to, but I want to include a label for the solutions which is what I am attempting to do with the print(paste()) portion at the bottom.


Solution

  • Using return() in this case is kind of like clearing the object(s). So printing "A" after using return won't do as expected. Instead, if you'd like to print "output" before printing the other statements, use print(output); then have the last line be return(), while using invisible(output) inside that function so that "output" doesn't print twice.

    Try this:

    TrapGeo<-function(b,m,y){ 
      A=((b+m*y)/y)
      #Flow Area
      P=(b+2*y*(sqrt(1+(m^2))))
      #Wetted Perimeter
      R=A/P
      #Hydraulic Radius
      B=b+2*m*y
      #Top Water Width
      D=A/B
      #Hydraulic Depth
      output=c(A, P, R, B, D)
      print(output)
      print(paste("Flow Area =", A)) 
      print(paste("Wetted Perimeter =", P)) 
      print(paste("Hydraulic Radius =", R)) 
      print(paste("Top Water Width =", B)) 
      print(paste("Hydraulic Depth =", D))
      return(invisible(output))
    }
    
    TrapGeo(1,2,3)
    

    Output:

    [1]  2.3333333 14.4164079  0.1618526 13.0000000  0.1794872
    [1] "Flow Area = 2.33333333333333"
    [1] "Wetted Perimeter = 14.4164078649987"
    [1] "Hydraulic Radius = 0.161852616489741"
    [1] "Top Water Width = 13"
    [1] "Hydraulic Depth = 0.179487179487179"