使用目录替换R中向量中的值

问题描述 投票:0回答:2

Im导入价值和货币数据,以及其他特征。货币是字符串,我需要用数字ID代替所有货币。我的确有一个包含所有货币和ID的矩阵作为目录。

我的矩阵看起来像

main <- cbind(c("toys", "food"),c(345, 45), c("USD", "EUR"))
cat<-cbind(c("USD", "EUR"), c(1, 2))

我想要的结果是针对

main
[toys,  345,  1
 food,  45,   2]
r substitution catalog
2个回答
0
投票

也许:

main[,3] <- cat[,2][match(main[,3], cat[,1])]

输出:

     [,1]   [,2]  [,3]
[1,] "toys" "345" "1" 
[2,] "food" "45"  "2" 

0
投票

我们可以使用

i1 <- match(main, cat[,1])
replace(main, !is.na(i1), cat[,2][i1])
© www.soinside.com 2019 - 2024. All rights reserved.