我有8个变量作为Var1-Var8。我想根据用户的选择找到他们中的2个之间的交叉产品。我从用户那里获取了2个输入,当它试图计算时,结果无法计算,因为找不到Var(x)。如何将用户的输入作为函数中的变量。我尝试了Var(x),Varx和Var$x,但它不起作用。已经谢谢你了。
findCrossProduct=function(x,y){
print("which variables do you want to see the cross-product between ?")
x=readline("Enter the first variable :")
y=readline("Enter the second variable :")
>> cp=sum(Var(x)*Var(y))-(sum(Var(x)*sum(Var(y))/length(Var(y))))
print(paste("Cross-product betwen variable ",x,"and variable",y,"is",cp))
}发布于 2020-05-02 20:37:03
应该在函数中调用整个数据帧。
findCrossProduct=function(df){
print("which variables do you want to see the cross-product between?")
x = readline("Enter the first variable: ")
y = readline("Enter the second variable: ")
cp = sum(df[x] * df[y]) - (sum(df[x])*sum(df[y])/nrow(df[y]))
print(paste("Cross-product between variable", x, "and variable", y, "is", cp))
}输出为
> findCrossProduct(data)
[1] "which variables do you want to see the cross-product between?"
Enter the first variable: Var2
Enter the second variable: Var3
[1] "Cross-product between variable Var2 and variable Var3 is 0.200000000000045"确保我使用的叉积公式是正确的。
https://stackoverflow.com/questions/61558276
复制相似问题