Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a vector in R using variable names

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

like image 252
Vik G Avatar asked Mar 08 '26 14:03

Vik G


2 Answers

You can use structure:

school_name = "coolSchool"
colors <- structure(c("yellow", "red", "orange"), .Names = c("School1","School2", school_name))
like image 120
Andre Elrico Avatar answered Mar 10 '26 04:03

Andre Elrico


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

colors <- c("yellow", "red", "orange")
names(colors) <- c("School1", "School2", school_name)
like image 31
GordonShumway Avatar answered Mar 10 '26 04:03

GordonShumway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!