The codes are as follows
l1<-list(1,2)
names(l1)<-c("a","b")
l1$"b"
a<-"b"
l1$a
The output for l1$"b"
is 2
,but for l1$a
is 1
.
This is not consistent.I don't know why and how to deal with it.
I hope you can help me! Thank you!
CodePudding user response:
You can use this functional notation
a<-"b"
`[[`(l1 , a)
#> 2
CodePudding user response:
To directly respond to your question about why this is the case: unlike the [
and [[
operators, the $
operator does not allow computed indices, i.e. The name
used to index into x
as in x$name
must be a literal character string or symbol.
So, the semantics of l1$a is something like:
get(quote(a), envir = as.environment(l1), inherits = FALSE)
# Lightly modified from ?`$` for clarity
As langtang and Mohamed have noted above, you can use the [
or [[
operators instead which do allow computed indices.