मुझे पसंद है purrr::when
और यहां दिए गए अन्य आधार समाधान सभी शानदार हैं, लेकिन मैं कुछ अधिक कॉम्पैक्ट और लचीला चाहता था इसलिए मैंने फ़ंक्शन pif
(पाइप अगर) डिजाइन किया , तो कोड देखें और जवाब के अंत में डॉक्टर को देखें।
तर्क या तो फ़ंक्शन के भाव हो सकते हैं (सूत्र संकेतन समर्थित है), और इनपुट डिफ़ॉल्ट रूप से अपरिवर्तित है यदि स्थिति है FALSE
।
अन्य उत्तरों से उदाहरणों पर प्रयुक्त:
data.frame(a=1:2) %>%
mutate(b=a^2) %>%
pif(~b[1]>1, ~mutate(.,b=b^2)) %>%
mutate(b=b^2)
1:3 %>% pif(sum(.) < 25,sum,0)
1 %>% pif(TRUE,~. + 1) %>% `*`(2)
1 %>% `+`(1) %>% pif(TRUE ,~ .+1)
अन्य उदाहरण:
iris %>% pif(is.data.frame, dim, nrow)
iris %>% pif(~is.numeric(Species),
~"numeric :)",
~paste(class(Species)[1],":("))
iris %>% pif(nrow(.) > 2, head(.,2))
iris %>% pif(TRUE, dim, warning("this will be evaluated"))
iris %>% pif(TRUE, dim, ~warning("this won't be evaluated"))
समारोह
pif <- function(x, p, true, false = identity){
if(!requireNamespace("purrr"))
stop("Package 'purrr' needs to be installed to use function 'pif'")
if(inherits(p, "formula"))
p <- purrr::as_mapper(
if(!is.list(x)) p else update(p,~with(...,.)))
if(inherits(true, "formula"))
true <- purrr::as_mapper(
if(!is.list(x)) true else update(true,~with(...,.)))
if(inherits(false, "formula"))
false <- purrr::as_mapper(
if(!is.list(x)) false else update(false,~with(...,.)))
if ( (is.function(p) && p(x)) || (!is.function(p) && p)){
if(is.function(true)) true(x) else true
} else {
if(is.function(false)) false(x) else false
}
}