Search code examples
rlistunexpected-token

Unexpected sign error when creating a list


I am trying to create a color list for specific levels of two factors. The parameters are the following:

> df.coldata
        Condition  Tank
R235      Control    T6
R236  LowExposure    T6
R239 HighExposure    T6
R241      Control    T8
R242  LowExposure    T8
R245 HighExposure    T8
R247      Control T14_3
R248  LowExposure T14_3
R250 HighExposure T14_3

As I don't want to manually fill in the Tank numbers or Condition I was trying to create a list using assigned variables like this:

### Specify colors ####
Tanks <- levels(df.coldata$Tank)
Conditions <- levels(df.coldata$Condition)

ann_colors <- list(
  Condition = c(Conditions[1]="lightskyblue", # This doenst work ... BUGS here!!!
                Conditions[3]="royalblue1",
                Conditions[2]="navyblue"),
  Tank = c(Tanks[1]="gray90",
           Tanks[2]="gray65",
           Tanks[3]="gray40")
)

But this creates an error telling me:

Error: unexpected '=' in:
"ann_colors <- list(
  Condition = c(Conditions[1]="

When I run the code with:

ann_colors <- list(
  Condition = c(Control="lightskyblue",
                LowExposure="royalblue1",
                HighExposure="navyblue"),
  Tank = c(T14_3="gray90",
           T6="gray65",
           T8="gray40")
)

it works like a charm. What am I doing wrong? Am I missing something?


Solution

  • Use setNames instead:

    ann_colors <- list(
      Condition = setNames(c("lightskyblue", "royalblue1", "navyblue"), Conditions),
      Tank = setNames(c("gray90", "gray65", "gray40"), Tanks)
      )
    

    The reason your code errors is that we are trying to assign a new value to Conditions/Tanks within c(). Below would work, and will replace the 1st value of Conditions to "lightskyblue", but this is not what we want:

    Conditions[1] = "lightskyblue"
    Conditions
    # [1] "lightskyblue" "HighExposure" "LowExposure" 
    

    And wrapping it in c() throws the error:

    c(Conditions[1] = "lightskyblue")
    # Error: unexpected '=' in "c(Conditions[1] ="