首页 > 解决方案 > 如何使用用户输入的数字作为变量?

问题描述

我有 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))

}

标签: rfunctionvectorstatisticscomputer-science

解决方案


应该在函数中调用整个数据框。

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"

确保我使用的叉积公式是正确的。


推荐阅读