词典的按键我创建了一个字典是这样访问R中
dict = new.env()
key <- "test"
dict$key <- 20
但是,当我想字典的关键,我这样做
print(ls(dict))
但什么是返回是“关键“而不是”测试“。
我试着这样做,以及
dict[["key"]] <- 20
,但我得到了相同的结果。那么我怎样才能访问我的字典的键?
词典的按键我创建了一个字典是这样访问R中
dict = new.env()
key <- "test"
dict$key <- 20
但是,当我想字典的关键,我这样做
print(ls(dict))
但什么是返回是“关键“而不是”测试“。
我试着这样做,以及
dict[["key"]] <- 20
,但我得到了相同的结果。那么我怎样才能访问我的字典的键?
您可以使用环境或列表作为词典(个人而言,我更喜欢后者),以这样的方式
### using environment as dictionary
dict <- new.env()
dict[["key 1"]] <- 20
dict[["key 2"]] <- "ABC"
# let's see the keys:
ls(envir = dict)
# access by name:
dict[["key 1"]]
dict[["key 2"]]
### using list as dictionary
dict <- list()
dict[["key 1"]] <- 20
dict[["key 2"]] <- "ABC"
# let's see the keys:
names(dict)
# access by name:
dict[["key 1"]]
dict[["key 2"]]
# of course, in both case you can use a character variable to define the key, e.g. :
myKey <- "key 3"
dict[[myKey]] <- 123
print(dict[[myKey]])
# > [1] 123
它的工作原理。谢谢 – user3841581
但是现在如果我使用第二种情况,现在是否像列表一样迭代它?我的意思是遍历所有密钥 – user3841581
我不确切知道你需要什么,但是例如你可以使用循环'for(n in names(dict))print(dict [[n]])'来迭代所有的值, – digEmAll
我想创建这样一个字典:
> dict<-c(1:20)
> names(dict)<-letters[1:20]
> dict
a b c d e f g h i j k l m n o p q r s t
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> dict["t"]
t
20
'key'没有出现在你没有放入的环境中。尝试'print(key)'看看''test''还在那里。 –
的确是它的实际关键。请原谅我的无知,我该怎么说呢?它不是字典$ key <-value或dict [[“key”]] ???? – user3841581