Home > OS >  Return true only if there is a absolute match
Return true only if there is a absolute match

Time:11-11

Is there a way to return true only if there is a absolute match. Example

> total_years <- as.factor(c("2020","2021"))
> total_years
[1] 2020 2021
Levels: 2020 2021
> all(total_years %in% c("2017","2018","2019", "2020", "2021"))
[1] TRUE

It is returning True since 2020 and 2021 are present in total_years. But the output should be false, since there are other values (2017, 2018, 2019)

Basically it should return TRUE only if it also exists 2020 and 2021 only

CodePudding user response:

You can find the documentation with ?"%in%":

returns a logical vector indicating if there is a match or not for its left operand.

Could also use setequal().

setequal(total_years, c("2017","2018","2019", "2020", "2021"))

CodePudding user response:

You could simply reverse the order of the arguments in the %in% statement, so you are asking whether each of the left hand arguments in the right hand arguments:

all(c("2017","2018","2019", "2020", "2021") %in% total_years)
[1] FALSE

and

> all( c("2020", "2021") %in% total_years)
[1] TRUE
  •  Tags:  
  • r
  • Related