[R] how to combine logic test on vectors in R?
Luigi Marongiu
m@rong|u@|u|g| @end|ng |rom gm@||@com
Thu Sep 30 17:51:02 CEST 2021
Yes, but the && should work within `unique(df_b$q) == ""` because the
test should be: (IF THE DATAFRAME HAS ZERO ROW) OR (ALL THE ELEMENTS
OF $q ARE EMPTY) THEN (PRINT empty).
Can I collapse the TRUE FALSE of `unique(df_b$q) == ""`into a single FALSE?
On Thu, Sep 30, 2021 at 4:28 PM Sarah Goslee <sarah.goslee using gmail.com> wrote:
>
> Hi,
>
> The OR operator you used is working as expected: || starts from the
> left and evaluates only enough of the options to determine the
> results. The first test is TRUE, so the result is TRUE. It sounds
> like you might actually want an AND operator, & or &&, which will only
> return TRUE if all elements are TRUE,
>
> More on logical operators:
> https://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html
>
> Sarah
>
> On Thu, Sep 30, 2021 at 9:07 AM Luigi Marongiu <marongiu.luigi using gmail.com> wrote:
> >
> > Hello,
> > I have two data frames, each with three rows:
> > ```
> > df_a <- data.frame(a = letters[1:3], b = LETTERS[1:3], q = c("", "", ""),
> > stringsAsFactors = FALSE)
> > df_b <- data.frame(a = letters[4:6], b = LETTERS[4:6], q = c("", "", "1.5"),
> > stringsAsFactors = FALSE)
> > ```
> > I need to test whether the dataframe has been selected and if there is
> > a value in the q column. I combined in the following test:
> > ```
> > if (nrow(df_a) == 0 || unique(df_a$q) == "") {
> > print("empty")
> > }
> > if (nrow(df_b) == 0 || unique(df_b$q) == "") {
> > print("empty")
> > }
> > ```
> > The test for df_a worked as expected:
> > ```
> > > nrow(df_a) == 0
> > [1] FALSE
> > > unique(df_a$q) == ""
> > [1] TRUE
> > > (nrow(df_a) == 0 || unique(df_a$q) == "")
> > [1] TRUE
> > > if (nrow(df_a) == 0 || unique(df_a$q) == "") {
> > + print("empty")
> > + }
> > [1] "empty"
> > ```
> > but the one for df_b did not:
> > ```
> > > nrow(df_b) == 0
> > [1] FALSE
> > > unique(df_b$q) == ""
> > [1] TRUE FALSE
> > > (nrow(df_b) == 0 || unique(df_b$q) == "")
> > [1] TRUE
> > > unique(df_b$q)
> > [1] "" "1.5"
> > ```
> > I say that it did not work because unique(df_b$q) IS NOT "", hence
> > `(nrow(df_b) == 0 || unique(df_b$q) == "")` should be FALSE, instead R
> > evaluated the first element of unique(df_b$q) == "", which is TRUE.
> > How can I properly implement a logic test on vectors?
> > Thank you
> >
> > ______________________________________________
> > R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
>
>
> --
> Sarah Goslee (she/her)
> http://www.sarahgoslee.com
--
Best regards,
Luigi
More information about the R-help
mailing list