3

我有两个向量:

A <- c(1,3,5,6,4,3,2,3,3,3,3,3,4,6,7,7,5,4,4,3) # 7 unique values
B <- c("a","b","c","d","e","f","g")   # 7 different values

我想将 B 的值与 A 匹配,以便 A 中的最小值从 B 中获取第一个值并继续到最大值。

上面的例子是:

A:        1 3 5 6 4 3 2 3 3 3 3 3 4 6 7 7 5 4 4 3
assigned: a c e f d c b c c c c c d f g g e d d c
4

3 回答 3

6

试试这个:

A <- c(1,3,5,6,4,3,2,3,3,3,3,3,4,6,7,7,5,4,4,3)
B <- letters[1:7]

B[match(A, sort(unique(A)))]
#  [1] "a" "c" "e" "f" "d" "c" "b" "c" "c" "c" "c" "c" "d" "f" "g"
# [16] "g" "e" "d" "d" "c"
于 2012-12-07T16:41:41.017 回答
3

处理@JoshO'Brien 解决的一般情况的另一个选项是

B[as.numeric(factor(A))]
# [1] "a" "c" "e" "f" "d" "c" "b" "c" "c" "c" "c" "c" "d"
# [14] "f" "g" "g" "e" "d" "d" "c"

A2<-ifelse(A > 4, A + 1, A)
# [1] 1 3 6 7 4 3 2 3 3 3 3 3 4 7 8 8 6 4 4 3
B[as.numeric(factor(A2))]
# [1] "a" "c" "e" "f" "d" "c" "b" "c" "c" "c" "c" "c" "d"
# [14] "f" "g" "g" "e" "d" "d" "c"

但是,以下基准显示此方法比@JoshOBrien 的慢。

library(microbenchmark)
B <- make.unique(rep(letters, length.out=1000))
A <- sample(seq_along(B), replace=TRUE)
unique_sort_match <- function() B[match(A, sort(unique(A)))]
factor_as.numeric <- function() B[as.numeric(factor(A))]
bm<-microbenchmark(unique_sort_match(), factor_as.numeric(), times=1000L)
plot(bm)

在此处输入图像描述

于 2012-12-07T19:15:40.453 回答
2

要详细说明@Josh 回答中的评论:

如果A确实代表了元素的排列B (即,其中 a 1inA代表 的第一个元素B,a 4inA代表 的第四个元素B,等等),那么正如@Matthew Plourde 指出的那样,您可能只想简单地A使用索引到B

B[A]

如果 A 不代表B的排列,那么您应该使用@Josh 建议的方法

于 2012-12-07T18:35:11.537 回答