使用R编程功能命令

时间:2017-09-02 03:48:06

标签: r function return labels

刚刚学习R编程,我正试图找到一种方法,用我从函数中获得的解决方案来包含描述。例如,如果我解决了Area,我希望函数说" Area = 2"而不仅仅是" 2"。我已经尝试过打印/粘贴命令,但对于我的生活,我尝试过的所有不同变化都不能使用函数命令。也许我错过了一些简单的东西?

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

到目前为止,该函数只返回我要求的输出,但是我想要为解决方案添加一个标签,这就是我尝试使用print(paste())部分底部。

2 个答案:

答案 0 :(得分:1)

在这种情况下使用 return()就像清除对象一样。所以在使用return之后打印“A”将不会按预期执行。相反,如果您想在打印其他语句之前打印“输出”,请使用print(输出);然后让最后一行为return(),同时在该函数中使用不可见(输出),以便“输​​出”不会打印两次。

试试这个:

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)

输出:

[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"

答案 1 :(得分:0)

以下是我要访问函数中计算的数据的方法,包括格式化的输出:

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

    # ready to print 
    output <- paste("Flow Area = ", A, "\n",
        "Wetted Perimeter = ", P, "\n",
        "Hydraulic Radius = ", R, "\n",
        "Top Water Width = ", B,  "\n",
        "Hydraulic Depth = ", D, "\n", sep = "" )

    # return both numbers and the formatted output
    return( list( c( A, P, R, B, D ), output ) )
}

现在,您可以使用您的函数为任何变量赋值,同时确保屏幕上不打印任何内容:

x <- TrapGeo( 1, 2, 3 )

现在或在以后的任何阶段,您都可以使用列表符号和cat()表示在屏幕上显示格式化数据(或将其保存到文件中):

cat( x[[2]] )
Flow Area = 2.33333333333333
Wetted Perimeter = 14.4164078649987
Hydraulic Radius = 0.161852616489741
Top Water Width = 13
Hydraulic Depth = 0.179487179487179

同时,您可以将数据作为数字进行访问以供进一步使用:

x[[1]][3]
[1] 0.1618526