2

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

3 Answers 3

5

You can use structure:

school_name = "coolSchool"
colors <- structure(c("yellow", "red", "orange"), .Names = c("School1","School2", school_name))
Sign up to request clarification or add additional context in comments.

Comments

2

You can just set the names of the colors using names():

colors <- c("yellow", "red", "orange")
names(colors) <- c("School1", "School2", school_name)

1 Comment

Thanks a ton Gordon.
1

This also works:

school_name <- "school3"
colors <- c("School1" = "yellow", "School2" = "red")
colors[school_name] <- "Orange"
# School1  School2  school3 
# "yellow"    "red" "Orange" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.