我正在尝试使用patchwork
包编写一个函数,其中根据函数中传递的参数显示图。我尝试了下面的方法,将未在函数中传递的对象设置为 NULL。但是,它仅在第一个对象不同于 NULL 时才有效。有什么想法吗?
# 1. PACKAGES
library(tidyverse)
library(patchwork)
# 2. DATA
data = starwars
# 3. FUNCTION
plot_people = function (homeworld = c("Tatooine", "Naboo", "Alderaan")) {
p1 = if (is.element("Tatooine", homeworld)) {
data %>%
filter(homeworld == "Tatooine") %>%
ggplot(aes(x = mass, y = height,
label = ifelse(species == "Human", name, NA))) +
geom_point() +
geom_label()
} else {
NULL
}
p2 = if (is.element("Naboo", homeworld)) {
data %>%
filter(homeworld == "Naboo") %>%
ggplot(aes(x = mass, y = height,
label = ifelse(species == "Human", name, NA))) +
geom_point() +
geom_label()
} else {
NULL
}
p3 = if (is.element("Alderaan", homeworld)) {
data %>%
filter(homeworld == "Alderaan") %>%
ggplot(aes(x = mass, y = height,
label = ifelse(species == "Human", name, NA))) +
geom_point() +
geom_label()
} else {
NULL
}
# how to write this line in order to plot only objects in homeworld argument?
p1 + p2 + p3
}
# 4. RESULTS
plot_people(homeworld = c("Naboo", "Tatooine"))
plot_people(homeworld = c("Naboo", "Alderaan"))
#> NULL
由reprex 包于 2020-06-07 创建(v0.3.0)