拥有"项目键的R列表"和#34;项目键的唯一键值对的一个数据帧"和相应的"项目名称",我想添加这些"项目名称"在另一个列表中,对应于项目键的原始列表。请查看下面的示例代码,以便更好地了解我的要求。有什么建议吗?
# 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"
答案 0 :(得分:1)
通常我喜欢使用命名向量。
在您的情况下,您只需使用Keys
作为Names
names (Names) <- Keys
lapply (ItemsList_Keys, function (x) Names[x])
如果是Keys
向量,请小心将其转换为字符。