r - 如何使用用户输入的数字作为变量?
问题描述
我有 8 个变量作为 Var1-Var8。我想通过用户的选择找到其中两个之间的交叉产品。我从用户那里获取 2 个输入,当它尝试计算时,由于找不到 Var(x),因此无法计算结果。如何将用户的输入作为函数中的变量。我尝试了 Var(x),Var[x] 和 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))
}
解决方案
应该在函数中调用整个数据框。
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"
确保我使用的叉积公式是正确的。
推荐阅读
- javascript - 从 ISO 字符串时刻 JS 库更新日期或时间
- python - TypeError:“follow_symLinks”是此函数的无效关键字参数
- java - 应用自定义哈希函数时如何读取文件
- reactjs - 在反应中通过地图更新开关状态渲染
- python - 我正在尝试使用 Python 中的指数平滑来预测数据。然而,在拟合模型后, Forecast() 不接受步骤作为参数
- pine-script - 难以向 Pine 脚本添加警报
- go - 关闭可能是 os.Stdin 的 io.Reader
- python - 我如何使用 vanilla JavaScript 在 Django 中发送 ajax 请求
- java - 我不知道为什么会出现这个错误,请帮助我
- awk - How to check if a string contains at least one letter different from 4 using bash or awk