How can I create a new column with values depending on the matrix / search logic?
I am trying to create a column that has values depending on matrix or logic solution as shown below.
Some Dummy-Data:
SomeDiscreteScale<-c("Black", "Black", "Red", "Green", "Blue", "Blue", "Black")
AccordingValue<-c(1:7)
TemplateData<-data.frame(SomeDiscreteScale, AccordingValue)
Logic for assigning values:
a<-c("Black", "Red", "Green", "Blue")
b<-c(1:4)
SolvingLogic<-data.frame(a,b)
The end result should look like this:
solution<-c(1,1,2,3,4,4,1) solution<-cbind(TemplateData, solution) solution
The way I am doing it now is Dummy data subset to Discrete values (here it will be black, red, green and blue), add the new value you want and then bind the data again. This is, of course, terribly inconvenient. But how can I make it easier?
Many thanks.
you can use match
TemplateData$solution <- match(TemplateData$SomeDiscreteScale, SolvingLogic$a)
TemplateData$solution
#[1] 1 1 2 3 4 4 1
If SolvingLogic$b
have some other meaning, for example
SolvingLogic$b <- letters[c(4,3,7,8)]
TemplateData$solution <- SolvingLogic$b[match(TemplateData$SomeDiscreteScale,
SolvingLogic$a)]
TemplateData$solution
#[1] "d" "d" "c" "g" "h" "h" "d"
In addition to, match
you can take a look merge
(but R base merge
can be slow and always seems funny with line orders):
merge(TemplateData, SolvingLogic, by.x = "SomeDiscreteScale", by.y = "a")
# SomeDiscreteScale AccordingValue b
# 1 Black 1 1
# 2 Black 2 1
# 3 Black 7 1
# 4 Blue 5 4
# 5 Blue 6 4
# 6 Green 4 3
# 7 Red 3 2
You can convert to factor
with the levels argument set to a
and then to numeric
:
transform(TemplateData, solution = as.numeric(factor(SomeDiscreteScale, levels = a)))
# SomeDiscreteScale AccordingValue solution
#1 Black 1 1
#2 Black 2 1
#3 Red 3 2
#4 Green 4 3
#5 Blue 5 4
#6 Blue 6 4
#7 Black 7 1
Just in case your actual "b" values in the search are more complex than 1: 4, you can still use this approach with a slight modification:
b <- letters[4:7] # using some characters for the lookup
transform(TemplateData, solution = b[as.numeric(factor(SomeDiscreteScale, levels = a))])
# SomeDiscreteScale AccordingValue solution
#1 Black 1 d
#2 Black 2 d
#3 Red 3 e
#4 Green 4 f
#5 Blue 5 g
#6 Blue 6 g
#7 Black 7 d