问题
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.
回答1:
You can use match
to look up each element of Matrix
in the Response
column of Values
and then grabbing the corresponding Description
value:
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"
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 to as.character
and 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
Data:
Mat2 <- data.frame(Muni = c("Town1", "Town2", "Town3", "Town4", "Town5"),
Company1 = factor(c(0,4,2,8,1)),
Company2 = factor(c(5,5,0,1,4)),
Company3 = factor(c(1:5)),
Company4 = factor(c(8,4,3,1,8)))
回答2:
an alternative dplyr
solution
# 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
if 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))
来源:https://stackoverflow.com/questions/35002102/replace-numeric-values-for-text-values