简体   繁体   English

使用变量名称在R中创建向量

[英]create a vector in R using variable names

I have a variable called school_name 我有一个名为school_name的变量

I am creating a vector to define colors that I will use later in ggplot2. 我正在创建一个向量来定义颜色,这些颜色将在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. 在我的代码中,我将变量school_name用于某些逻辑,希望将其添加为向量的第三个元素。 The value changes in my for loop and cannot be hard-coded. 该值在我的for循环中更改,无法进行硬编码。

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 有人可以帮我吗

You can just set the names of the colors using names() : 您可以使用names()设置颜色的names()

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

You can use structure : 您可以使用structure

school_name = "coolSchool"
colors <- structure(c("yellow", "red", "orange"), .Names = c("School1","School2", school_name))

This also works: 这也适用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM