整数型下标
price.map <- c(68, 88, 168)
设某个收银员在一天内分别售出礼品编号为3,2,1,1,2,2,3, 可以用如下的映射方式获得售出的这些礼品对应的价格:
items <- c(3,2,1,1,2,2,3)
y <- price.map[items]; print(y)
## [1] 168 88 68 68 88 88 168
字符型
把带有元素名的R向量看成是元素名到元素值的映射表。 比如,设sex为10个学生的性别(男、女)
sex <- c("男", "男", "女", "女", "男", "女", "女", "女", "女"
, "男")#“男” “女”为“下标”
希望把每个学生按照性别分别对应到蓝色和红色。 首先建立一个R向量当作映射
sex.color <- c("男"="blue", "女"="red")
用R向量sex.color当作映射,可以获得每个学生对应的颜色
cols <- sex.color[sex]; print(cols)
男 男 女 女 男 女 女 女 女 男
"blue" "blue" "red" "red" "blue" "red" "red" "red" "red" "blue"
这样的映射结果中带有不必要的元素名, 用unname()函数可以去掉元素名
unname(cols)
[1] "blue" "blue" "red" "red" "blue" "red" "red" "red" "red" "blue"