课程: R for Data Science: Lunch Break Lessons

Any/all

- [Narrator] Boolean vectors can contain multiple true-false values, and there are instances where you want to test those vectors for the status of the contents. Is it all false, is it all true, is some of it true, is none of it true? And for that, we've got all and any. To demonstrate this, I've created three vectors. One of them, called allFALSE that contains all false Boolean values, another called allTrue, it contains all true, and a third called someTRUE, which contains some true values and some false values. Let's test those. We'll start with any, a n y, and I'll type in a vector, we'll test allFALSE, and what it's asking for is are any values in allFALSE true, and it says FALSE, no. Corresponding, I can type in any(allTRUE) and it's going to come back and say well, sure, any of the values of allTRUE are true, so that's correct. Well, so the third instance, which is any(someTRUE) returns true, because some values of TRUE are true, so yes, we return a true. Now, we can look at all, and if I type in all(allFALSE), it comes back as false, because all of the values of false are not true. If I type in all(allTRUE), and I test all true, it's going to come back and say true, because yes, all of the values of allTRUE are true, so that's correct. Now, the third instance, which is all(someTRUE), will come back and say false, because not all of the values of someTRUE are true, so it's going to return false. That's any and alls, now there are a lot of corresponding functions that go with this, so for example, if I type in all.equal, and I give all.equal a group of values, let's say three, comma, 2+1, which equals three, and as.integer(pi), which also equals three, we should get back true because all of those values are equal to three. Now, there's another similar function to any, which is anyDuplicated, and it says is there anything that's duplicated in this string? So I can type in someTRUE, and it will come back and it gives me a number, and that number corresponds to the values that are duplicated, so if we look at someTRUE, we'll see that the third value is a duplicate of the second value. If I typed in anyDuplicated and I type in allTRUE, I get two, and that's because if we look at allTRUE, the second value is a duplicate of the first value. There's also anyNA, and if I type in someTRUE, this will come back and say false because none of someTRUE correspond to NA. I can make this come back as true if I typed in anyNA, and we can combine, let's go with someTRUE and then a comma, and now we'll put in an NA, so if I hit return, now I get true, because anyNA is saying one of the elements that was passed to it is NA, so, that's true. So that's any and all, it's used to test vectors, primarily Boolean vectors, for values to see if any of them are true, or if all of them are true.

内容