【问题标题】:How can I use the number entered by the user as a variable?如何使用用户输入的数字作为变量?
【发布时间】:2020-08-16 21:00:15
【问题描述】:

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

}

【问题讨论】:

  • 你试过as.numeric(x)吗?
  • 我实际上是 R 新手。你能提供更多关于as.numeric(x)@RuiBarradas的用法的详细信息
  • readline 之后运行x <- as.numeric(x)y 相同。这是因为 readline 返回值属于 "character"sumvar 类,仅适用于数字数据。注意:R 区分大小写,它是var,而不是Var

标签: r function vector statistics computer-science


【解决方案1】:

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

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"

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多