簡體   English   中英

匹配R中兩個向量的值

[英]Matching values from two vectors in R

我有兩個向量:

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

嘗試這個:

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"

處理@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)

在此輸入圖像描述

詳細說明@Josh的答案中的評論:

如果A事實上確實表示的元素的置換B (即,其中一個1A表示的第一個元素B ,一個4A表示在第4個元件B等),則如@Matthew Plourde指出的,你只想用A作為B的索引:

B[A]

如果A 不代表 B的排列,那么你應該使用@Josh建議的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM