I've searched various posts related to this question and still cannot find a solution.
I'm trying to apply multiple filters on a dataframe that involve if() statements that if a condition is met then it includes the individual filter inside {} in the set of filters, and if the statement is not met then it ignores that particular filter. Consider the follow base code that works perfectly although it doesn't include the if statements yet.
library(tidyverse)
llibrary(purrr)
library(dplyr)
Cb1 <- 0.75
Cb2 <- 1.0
Cb3 <- 20
Cb4 <- 8
test <- map(metrics, ~filter(.,
industry == "Technology",
price <= (median(price, na.rm = TRUE)) * Cb1,
ror >= (median(ror, na.rm = TRUE)) * Cb2,
debt <= Cb3,
periods >= Cb4,
price >= 0))
The code references a list of 3 dataframes titled "metrics" that I'm not including in the code for simplicity (which means that you won't be able to test this code). But it includes numerous columns of data, some of which include: industry, price, debt, periods, and ror. Which are the columns that I'm interested in filtering. Note that this includes a map function because it is performing the filtering on the 3 dataframes included in the list "metrics", but that is not important in my question.
I would like to add some if statements that check if the constants Cb are not equal to 0, then the filters inside {} are included in the set of multiple filters. But if the constants Cb are equal to 0, then this particular filter is excluded in the multiple set of filters (and the other filters still may apply). Through some research I thought that maybe using "else" after the {} and simply having nothing after "else" will achieve what I'm looking for. But it does not work. This is the code that I've tried using if statements inside the filter function, but again this does not work. To clarify, the code runs without errors, but the filters do not work properly.
Cb1 <- 0.75
Cb2 <- 0
Cb3 <- 20
Cb4 <- 8
test <- map(metrics, ~filter(.,
industry == "Technology",
if(Cb1 != 0) {price <= (median(price, na.rm = TRUE)) * Cb1} else
if(Cb2 != 0) {ror >= (median(ror, na.rm = TRUE)) * Cb2} else
if(Cb3 != 0) {debt <= Cb3} else
if(Cb4 != 0) {periods >= Cb4} else
price >= 0))
I feel like this something relatively simple like the syntax of where I place my {}, (), or even the commas. Or maybe it's some combination of boolean operators (& or |). But I can't seem to get it to work. Note that there are also some filters that don't include an if check as I want them to always apply.
I would normally try to include an expected outcome, but that is difficult since this is a set of filters on a dataframe that I cannot include. I'm hoping that someone can help with my syntax in the if statement code and that will solve the problem.
Any help is appreciated!
Aucun commentaire:
Enregistrer un commentaire