我有两个矩阵A和B.A是数据集,B是关于A的实例(行)所属的类的信息。 我需要将类信息添加到矩阵A,我不知道如何使用哪个函数? 矩阵示例:
A = [A a v c
B a d c
B s x d
C s c s]
B = [A 0
B 1
C 0]
我需要:
A = [A a v c 0
B a d c 1
B s x d 1
C s c s 0]
答案 0 :(得分:3)
您可以通过调用match
来确定与A的每一行对应的B行:
cbind(A, B[match(A[,1], B[,1]),2])
# [,1] [,2] [,3] [,4] [,5]
# [1,] "A" "a" "v" "c" "0"
# [2,] "B" "a" "d" "c" "1"
# [3,] "B" "s" "x" "d" "1"
# [4,] "C" "s" "c" "s" "0"
数据:
A <- matrix(c("A", "B", "B", "C", "a", "a", "s", "s", "v", "d", "x", "c", "c", "c", "d", "s"), nrow=4)
B <- matrix(c("A", "B", "C", 0, 1, 0), nrow=3)
答案 1 :(得分:2)
尝试:
library(qdapTools)
cbind(A, lookup(A, B))
给出了:
# [,1] [,2] [,3] [,4] [,5]
# [1,] "A" "a" "v" "c" "0"
# [2,] "B" "a" "d" "c" "1"
# [3,] "B" "s" "x" "d" "1"
# [4,] "C" "s" "c" "s" "0"