使用变量名在 R 中创建一个向量
create a vector in R using variable names
我有一个名为 school_name
的变量
我正在创建一个矢量来定义稍后将在 ggplot2 中使用的颜色。
colors <- c("School1" = "yellow", "School2" = "red", ______ = "Orange")
在我的代码中,我使用变量 school_name 来实现某些逻辑,希望将其添加为向量的第三个元素。我的 for 循环中的值发生变化,不能硬编码。
我尝试了以下方法,但它不起作用。
colors <- c("School1" = "yellow", "School2" = "red", get("school_name") = "Orange")
有人可以帮我解决这个问题
您可以使用 names()
:
设置颜色名称
colors <- c("yellow", "red", "orange")
names(colors) <- c("School1", "School2", school_name)
您可以使用 structure
:
school_name = "coolSchool"
colors <- structure(c("yellow", "red", "orange"), .Names = c("School1","School2", school_name))
这也有效:
school_name <- "school3"
colors <- c("School1" = "yellow", "School2" = "red")
colors[school_name] <- "Orange"
# School1 School2 school3
# "yellow" "red" "Orange"
我有一个名为 school_name
的变量我正在创建一个矢量来定义稍后将在 ggplot2 中使用的颜色。
colors <- c("School1" = "yellow", "School2" = "red", ______ = "Orange")
在我的代码中,我使用变量 school_name 来实现某些逻辑,希望将其添加为向量的第三个元素。我的 for 循环中的值发生变化,不能硬编码。
我尝试了以下方法,但它不起作用。
colors <- c("School1" = "yellow", "School2" = "red", get("school_name") = "Orange")
有人可以帮我解决这个问题
您可以使用 names()
:
colors <- c("yellow", "red", "orange")
names(colors) <- c("School1", "School2", school_name)
您可以使用 structure
:
school_name = "coolSchool"
colors <- structure(c("yellow", "red", "orange"), .Names = c("School1","School2", school_name))
这也有效:
school_name <- "school3"
colors <- c("School1" = "yellow", "School2" = "red")
colors[school_name] <- "Orange"
# School1 School2 school3
# "yellow" "red" "Orange"