我创建了一个函数,其中包含一系列与函数输入中的各种对象的减法和加法,我想知道如何执行这些操作,而不必在每次添加新对象时复制和粘贴现有代码.
a <- function(qt1,qt2,qt3,qt4,
cu1,cu2,cu3,cu4,
gpd1,gpd2,gpd3,gpd4,
cs1,cs2,cs3,cs4,
csp1,csp2,csp3,csp4,
cp1,cp2,cp3,cp4,
ms1,ms2,ms3,ms4,
ad1,ad2,ad3,ad4)
{
c1 = (qt1 * cu1) +gpd1 + cs1 + csp1+ce+cp1
c2 = (qt2 * cu2) +gpd2 + cs2 + csp2+ce+cp2
c3 = (qt3 * cu3) +gpd3 + cs3 + csp3+ce+cp3
c4 = (qt4 * cu4) +gpd4 + cs4 + csp4+ce+cp4
ct1 = (c1 * 0.4)+c1 + e/4+cap+ ms1+ qt1 *ad1
ct2 = (c2 * 0.4)+c2 + e/4+cap+ ms2+ qt2 *ad2
ct3 = (c1 * 0.4)+c3 + e/4+cap+ ms3+ qt3 *ad3
ct4 = (c1 * 0.4)+c4 + e/4+cap+ ms4+ qt4 *ad4
print("RU 1")
print(ct1/qt1)
print("RU 2")
print(ct2/qt2)
print("RU 3")
print(ct3/qt3)
print("RU 4")
print(ct4/qt4)
}
a(qt1=10,qt2=15,qt3=18,qt4=20,
cu1=5,cu2=2,cu3=12,cu4=17,
gpd1=2,gpd2=5,gpd3=8,gpd4=8,
cs1=2,cs2=4,cs3=2,cs4=5,
csp1=2,csp2=3,csp3=4,csp4=4,
cp1=2,cp2=2,cp3=2,cp4=2,
ms1=2,ms2=2,ms3=4,ms4=5,
ad1=1,ad2=2,ad3=3,ad4=4)
Run Code Online (Sandbox Code Playgroud)
这很简单。使用向量而不是将每个作为单独的参数传递。
# qt <- c(qt1, qt2, qt3, qt4)
# cu <- c(cu1, cu2, cu3, cu4)
qt <- c(1, 2, 3, 4)
cu <- c(1, 2, 3, 4)
Run Code Online (Sandbox Code Playgroud)
所有的操作在向量上都是一样的,所以你不必一遍又一遍地明确地执行表达式。
# Addition/Subtraction
qt + cu
[1] 2 4 6 8
# Multiplication
qt * cu
[1] 1 4 9 16
# Division
qt / 2
[1] 0.5 1.0 1.5 2.0
Run Code Online (Sandbox Code Playgroud)