Reputation: 639
I have a variable called school_name
I am creating a vector to define colors that I will use later in ggplot2.
colors <- c("School1" = "yellow", "School2" = "red", ______ = "Orange")
In my code I am using the variable school_name for some logic want to add that as the third element of my vector. The value changes in my for loop and cannot be hard-coded.
I have tried the following but it does not work.
colors <- c("School1" = "yellow", "School2" = "red", get("school_name") = "Orange")
Please can someone help me with this
Upvotes: 2
Views: 2315
Reputation: 47320
This also works:
school_name <- "school3"
colors <- c("School1" = "yellow", "School2" = "red")
colors[school_name] <- "Orange"
# School1 School2 school3
# "yellow" "red" "Orange"
Upvotes: 1
Reputation: 11480
You can use structure
:
school_name = "coolSchool"
colors <- structure(c("yellow", "red", "orange"), .Names = c("School1","School2", school_name))
Upvotes: 5
Reputation: 2056
You can just set the names of the colors using names()
:
colors <- c("yellow", "red", "orange")
names(colors) <- c("School1", "School2", school_name)
Upvotes: 2