contrast=list("1"="profit")
input=readline("please input")
please input1
input
[1] "1"
class(input)
[1] "character"
contrast[[input]]
[1] "profit"
contrast$"1"
[1] "profit"
contrast$input
NULL
Run Code Online (Sandbox Code Playgroud)
为什么 contrast$input 不等于 contrast$"1"?
输入值为"1",类也是字符.
eval(input)
[1] "1"
contrast$(eval(input))
Error: unexpected '(' in "contrast$("
contrast$eval(input)
Error: attempt to apply non-function
eval(paste(input))
[1] "1"
class(eval(paste(input)))
[1] "character"
contrast$eval(paste(input))
Error: attempt to apply non-function
contrast$(eval(paste(input)))
Error: unexpected '(' in "contrast$("
Run Code Online (Sandbox Code Playgroud)
有没有办法通过对比$ input获得价值?
这是不可能的.从文档(?Extract):
"两个[[和$选择列表中的单个元素.主要区别在于$不允许计算索引,而[[do.x $ name相当于x [["name",exact = FALSE]]"
通常,$用于交互式使用,但用于编程(脚本,函数等),您应该使用[[.