I am trying to give the words that I have in a matrix (90+) a numerical value to use in a further calculation.
I haven't really gotten anywhere with this. I have it written out as a function currently, but I need the words to be automatically detected from an Excel File matrix that I have saved in the project and turned into numerical values, instead of me writing them as inputs.
status <- function(color_input) {
if (color_input == "Red")
{ return(25)}
if (color_input == "Orange")
{ return(50)}
if (color_input == "Yellow")
{ return(70)}
if (color_input == "Green")
return(90)}
There are many ways of doing this, I think using case_when() inside a mutate() statement it is more simple and readable but it also can be done using your function, see this example:
df <- data.frame(stringsAsFactors = FALSE,
color = c("Red", "Orange", "Yellow", "Green"))
library(dplyr)
df %>%
mutate(color = case_when(color == "Red" ~ 25,
color == "Orange" ~ 50,
color == "Yellow" ~ 70,
color == "Green" ~ 90))
#> color
#> 1 25
#> 2 50
#> 3 70
#> 4 90
# Using your function
status <- function(color_input) {
if (color_input == "Red") {
return(25)
}
if (color_input == "Orange") {
return(50)
}
if (color_input == "Yellow") {
return(70)
}
if (color_input == "Green") {
return(90)
}
}
df %>%
rowwise() %>%
mutate(color = status(color))
#> Source: local data frame [4 x 1]
#> Groups: <by row>
#>
#> # A tibble: 4 x 1
#> color
#> <dbl>
#> 1 25
#> 2 50
#> 3 70
#> 4 90
@andresrcs If I'm looking at this correctly the reason this doesn't work is because I'm pulling the words "Red" "Orange" "Yellow" and "Green" in from an Excel file matrix (Real_Example_Data).
Is there a way to do this by telling it to use my object to pull the words from?
HealthStatus <- as.matrix(Real_Example_Data[,3])
Another way to do this is with the dplyrrecode function. Below is an example, using the built-in iris data frame. If you provide a data sample that looks like your real data, we can provide a tailored version of this approach.
In the first step, we create a named vector with the current and recoded values.
Could you turn this into a minimal REPRoducible EXample (reprex)? A reprex makes it much easier for others to understand your issue and figure out how to help.
If you've never heard of a reprex before, you might want to start by reading this FAQ: