I have a matrix of number values of 0-8 which I would like to replace with descriptive values. My current matrix is as follows:
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"
I would like to replace the numeric values with the following descriptive values
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"
I've tried
replace(Matrix,Values$Response,Values$Description)
but am not getting the new values being replaced by the initial numeric code.
an alternative
dplyr
solutionif you want to get back to a matrix you can obviously do
as.matrix(data.frame(Matrix) %>% mutate_each(funs(Values[,2][match(., Values[,1])]), -Muni))
You can use
match
to look up each element ofMatrix
in theResponse
column ofValues
and then grabbing the correspondingDescription
value:If instead your
Matrix
variable were really a data frame with the data stored as factors (as suggested in your comments), you could include a call toas.character
andunlist
:Data: