使用数据框查找列表 table

Using a data frame as a look up table for a list

有一个 "item keys" 的 R 列表和一个 "item keys" 和对应的 "item names" 唯一键值对的数据框,我想添加这些 "item names" 在另一个列表中,对应于项目键的原始列表。请查看下面的示例代码,以更好地了解我的要求。有什么建议吗?

# step 1: make the data fram of "item keys" and corresponding "item names"
Keys <- c("5763", "5832", "5767", "5768")
Names <- c("sugar", "milk", "coffee", "tea")
KeyNames <- data.frame(Keys, Names)

# step 2: make a list of items. Each list entry has a variable number of items. 
ItemsList_Keys  <- replicate(10, 
    sample(Keys, size = sample(1:5, size = 1, replace = T), 
    replace=T), simplify = F)

# Have a look at the ItemsList..
 print(ItemsList_Keys[1:2])
[[1]]
[1] "5767" "5768" "5763" "5767"

[[2]]
[1] "5832" "5763" "5832" "5768" "5763"

# step 3:
# then I would like to make a "ItemsList_Names", 
# similar to "ItemsList_Keys", but prividing the "Names" 
# corresponding to the "Keys".. 


ItemsList_Names <- # .. something ..


# .. that would result in a list as shown below:    
ItemsList_Names[1]
[[1]]
[1] "coffee" "tea" "sugar" "coffee"

通常我喜欢为此使用命名向量。

在您的情况下,您只需使用 Keys 作为 Names

的名称
names (Names) <- Keys
lapply (ItemsList_Keys, function (x) Names[x])

小心将您的Keys向量转换为字符,如果它是数字的话。