我有一个数据库,看起来像:

> database
     [,1] [,2] [,3] [,4]
[1,]    1    2    1    1
[2,]    2    2    3    4
[3,]    4    4    4    1


还有一个对应表,它是一个数据框:

> corresp
  number  name
1      1 name1
2      2 name2
3      3 name3
4      4 name4


如何在不使用循环的情况下用数据库中的相应名称替换数字?

(用于复制:)

database <- rbind(c(1, 2, 1, 1),
                  c(2, 2, 3, 4),
                  c(4, 4, 4, 1))
corresp <- data.frame(number = c(1, 2, 3, 4),
                      name = c("name1","name2","name3","name4"))

最佳答案

没有循环,甚至没有apply

database[] <- as.character(corresp$name)[match(database, corresp$number)]

database
#     [,1]    [,2]    [,3]    [,4]
#[1,] "name1" "name2" "name1" "name1"
#[2,] "name2" "name2" "name3" "name4"
#[3,] "name4" "name4" "name4" "name1"

07-28 08:10