함수에 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 패키지 (v0.3.0)에 의해 2020-06-07에 생성됨
의 각 요소에 대해 동일한 코드를 실행해야하므로 (또는 원하는 경우)를 homeworld
사용하여 반복 할 수 있습니다 . 이렇게하면 각 반복에 대한 요소가있는 목록이 반환되며 여기에는 플롯 (예 : , 등)이 포함됩니다. 이 목록은 각 요소를 반복적으로 결합하기 위해 d (또는 d)가 될 수 있습니다 .purrr::map
lapply
p1
p2
reduce
Reduce
+
library(tidyverse)
library(patchwork)
plot_people = function (homeworld = c("Tatooine", "Naboo", "Alderaan")) {
plots <- map(homeworld, function(hw){
starwars %>%
filter(homeworld == hw) %>%
ggplot(aes(x = mass, y = height,
label = ifelse(species == "Human", name, NA))) +
geom_point() +
geom_label()
})
reduce(plots, `+`)
}
plot_people(homeworld = c("Naboo", "Tatooine"))
plot_people(homeworld = c("Naboo", "Alderaan"))
또는 대신 플롯 목록을 허용하는 패치 워크 의 함수를 사용하여을 reduce(plots, `+`)
작성할 수 있습니다. 결과는 동일합니다.wrap_plots(plots)
wrap_plots()
더 일반적으로 패치 워크를 사용하기 전에 패싯을 고려해야합니다.
library(tidyverse)
plot_people = function (homeworld = c("Tatooine", "Naboo", "Alderaan")) {
starwars %>%
filter(homeworld %in% !!homeworld) %>%
ggplot(aes(x = mass, y = height,
label = ifelse(species == "Human", name, NA))) +
geom_point() +
geom_label() +
facet_wrap(~homeworld)
}
plot_people(homeworld = c("Naboo", "Tatooine"))
plot_people(homeworld = c("Naboo", "Alderaan"))
이 방법을 사용하면 어떤 행성이 무료인지 식별 할 수있는 멋진 패널 스트립 레이블을 얻을 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다