如何映射具有相同级别但长度不同的因素的名称?

How to map names of factors having identical levels but different length?

我有两个因子 tIDfff,水平相同但长度不同,分别为 45000000 和 23000:

> head(factor(tID))
Fungi Metazoa   Fungi   Fungi   Fungi   Fungi 
227321   79782   52586 1658174  573508   88771

Levels: 2 7 9 11 14 16 17 19 20 22 23 24 32 33 34 38 39 41 42 43 47 48 51 52 54 56 61 68 69 72 75 81 85 86 103 104 106 114 119 120 122 124 125 128 134 140 141 142 143 144 148 154 158 159 162 163 165 167 171 172 173 174 179 ... 1985254

head(fff)
[1] 4932   870730 34413  4932   4932   9606  
Levels: 2 7 9 11 14 16 17 19 20 22 23 24 32 33 34 38 39 41 42 43 47 48 51 52 54 56 61 68 69 72 75 81 85 86 103 104 106 114 119 120 122 124 125 128 134 140 141 142 143 144 148 154 158 159 162 163 165 167 171 172 173 174 179 ... 1985254

有没有更快的方法将名称从因子 tID 映射到 fff

我知道我可以使用 lappy()sapply() 来做到这一点,但是因子包含 450 万个元素,所以速度有点慢。

namesmatch:

names(fa) <- names(fb)[match(fa, fb)]

你得到:

> fa
 name_1  name_1  name_1  name_6  name_6  name_6 name_11 name_11 name_11 name_16 name_16 name_16 name_21 name_21 name_21 
      a       a       a       b       b       b       c       c       c       d       d       d       e       e       e 
Levels: a b c d e

对于问题中的新示例,这应该是:

names(fff) <- names(tID)[match(fff, tID)]

示例数据:

fa <- factor(rep(letters[1:5], each = 3))
fb <- factor(rep(letters[1:5], each = 5))
fb <- setNames(fb, paste0('name_',seq_along(fb)))