替换文本值的数值

时间:2016-01-25 20:50:52

标签: r replace lookup

我有一个数字值为0-8的矩阵,我想用描述性值替换它。我目前的矩阵如下:

Muni<-c("Town1","Town2","Town3","Town4","Town5")
Company1<-c(0,4,2,8,1)
Company2<-c(5,5,0,1,4)
Company3<-c(1:5)
Company4<-c(8,4,3,1,8)
(Matrix<-cbind(Muni,Company1,Company2,Company3,Company4))
#      Muni    Company1 Company2 Company3 Company4
# [1,] "Town1" "0"      "5"      "1"      "8"     
# [2,] "Town2" "4"      "5"      "2"      "4"     
# [3,] "Town3" "2"      "0"      "3"      "3"     
# [4,] "Town4" "8"      "1"      "4"      "1"     
# [5,] "Town5" "1"      "4"      "5"      "8"  

我想用以下描述性值

替换数值
Response<-c(1:8)
Description<-c("0-1","2-5","6-10","11-15","16-20","21-30","31+","I don't know")
(Values<-cbind(Response,Description))
#      Response Description   
# [1,] "1"      "0-1"         
# [2,] "2"      "2-5"         
# [3,] "3"      "6-10"        
# [4,] "4"      "11-15"       
# [5,] "5"      "16-20"       
# [6,] "6"      "21-30"       
# [7,] "7"      "31+"         
# [8,] "8"      "I don't know"

我试过

replace(Matrix,Values$Response,Values$Description)

但我没有将新值替换为初始数字代码。

2 个答案:

答案 0 :(得分:3)

您可以使用matchMatrix的{​​{1}}列中查找Response的每个元素,然后获取相应的Values值:

Description

如果您的Matrix[,-1] <- Values[match(Matrix[,-1], Values[,"Response"]),"Description"] Matrix # Muni Company1 Company2 Company3 Company4 # [1,] "Town1" NA "16-20" "0-1" "I don't know" # [2,] "Town2" "11-15" "16-20" "2-5" "11-15" # [3,] "Town3" "2-5" NA "6-10" "6-10" # [4,] "Town4" "I don't know" "0-1" "11-15" "0-1" # [5,] "Town5" "0-1" "11-15" "16-20" "I don't know" 变量确实是一个数据框,数据存储为因子(如评论中所示),则可以包含对Matrixas.character的调用:< / p>

unlist

数据:

Mat2[,-1] <- Values[match(as.character(unlist(Mat2[,-1])), Values[,"Response"]),"Description"]
Mat2
#    Muni     Company1 Company2 Company3     Company4
# 1 Town1         <NA>    16-20      0-1 I don't know
# 2 Town2        11-15    16-20      2-5        11-15
# 3 Town3          2-5     <NA>     6-10         6-10
# 4 Town4 I don't know      0-1    11-15          0-1
# 5 Town5          0-1    11-15    16-20 I don't know

答案 1 :(得分:1)

替代 dplyr解决方案

# install.packages("dplyr", dependencies = TRUE)
library(dplyr)
data.frame(Matrix) %>% 
    mutate_each(funs(Values[,2][match(., Values[,1])]), -Muni)
#     Muni     Company1 Company2 Company3     Company4
# 1 Town1         <NA>    16-20      0-1 I don't know
# 2 Town2        11-15    16-20      2-5        11-15
# 3 Town3          2-5     <NA>     6-10         6-10
# 4 Town4 I don't know      0-1    11-15          0-1
# 5 Town5          0-1    11-15    16-20 I don't know

如果你想回到矩阵,你显然可以as.matrix(data.frame(Matrix) %>% mutate_each(funs(Values[,2][match(., Values[,1])]), -Muni))