Home > Software design >  Using multiple if else in function
Using multiple if else in function

Time:11-13

I have the template code like this:

treatment.colors <- unlist(lapply(GSE8823.qc.rma$status, 
                               function (x) {if (x == "smoker") "red" else "navy"}))

This code makes the two groups: smoker and non-smoker into different colors. As the code says, if the x==smoker, the color is red, else the color is navy.

Now, I have four groups: G1,G2,G3,G4. I want to define 4 different colors correspondingly. Let us say, I want to G1=red, G2=navy, G3=yellow, G4=green.

My question is how can I rewrite this code to achieve this goal? Should I use another else if in the else part of template code? Should the code look like something this?

treatment.colors <- unlist(lapply(GSE8823.qc.rma$status, 
                               function (x) {if (x == "G1") "red" else if (x=="G2", "navy"), else if (x=="G3", "yellow"), else "green"}))

Thanks for helping~~!

CodePudding user response:

One neat solution is to use dplyr case_when function.

library(dplyr)

status = GSE8823.qc.rma$status

treatment.colors = case_when(
    status == "G1" ~ "red",
    status == "G2" ~ "navy",
    status == "G3" ~ "yellow",
    status == "G4" ~ "green",
)

Or more directly to table:

library(dplyr)

GSE8823.qc.rma = GSE8823.qc.rma %>%
    mutate(
        colors = case_when(
            status == "G1" ~ "red",
            status == "G2" ~ "navy",
            status == "G3" ~ "yellow",
            status == "G4" ~ "green",
        )
    )

If you want to stick to base R you could try using a named vector to store the label color matches:

test = c("G1", "G2", "G3", "G4")

get_color = function(label) {
    colors = c(
        "G1" = "red",
        "G2" = "navy",
        "G3" = "yellow",
        "G4" = "green"
    )
    return(colors[[label]])
}

colors = sapply(test, get_color)

Note that I used sapply here instead since it returns a vector by default, no need to unlist. Just makes it slightly cleaner.

CodePudding user response:

I like factor for these kinds of tasks. because it is vectorized, no need for lapply

#example
set.seed(10)
GSE8823.qc.rma <- data.frame(status = sample(c("G1","G2","G3","G4"), 10,replace = TRUE))
GSE8823.qc.rma
#>    status
#> 1      G3
#> 2      G1
#> 3      G2
#> 4      G4
#> 5      G4
#> 6      G3
#> 7      G4
#> 8      G2
#> 9      G3
#> 10     G3

#solution
treatment.colors <- factor(GSE8823.qc.rma$status, 
       levels = c("G1","G2","G3","G4"),
       labels = c("red", "navy", "yellow", "green")) |>
  as.character()

treatment.colors
#>  [1] "yellow" "red"    "navy"   "green"  "green"  "yellow" "green"  "navy"  
#>  [9] "yellow" "yellow"
  •  Tags:  
  • r
  • Related