Ff Yy
Ff Yy

Reputation: 247

Get value of list by name attribute in R

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

Why contrast$input is not equal to contrast$"1"?
the value of input is "1",the class is character too.

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$("

Is there no way to get the value via contrast$input?

Upvotes: 0

Views: 5123

Answers (1)

joran
joran

Reputation: 173527

This isn't possible. From the documentation (?Extract):

"Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]]"

In general, $ is intended for interactive use, but for programming (scripts, functions, etc.) you should use [[.

Upvotes: 6

Related Questions