课程: R for Data Science: Lunch Break Lessons

exists

- [Instructor] Don't reinvent the wheel. When you're running R, you shouldn't redefine something that's already existing. And a way to determine if something is already existing is to use the R command exists. So let's take a look at how to use exists to save your code some time and effort. In the code window on line two, I've created an if else statement. And the first thing that it says is if exists DefinedVector, then line three is a comment that says avoid repeating long and expensive routine. If DefinedVector already exists, you shouldn't redefine vector. Now, if DefinedVector doesn't exist, we'll drop down to line five and print it's NOT defined. So let's go ahead and run that and just see what happens if DefinedVector is not defined. No surprise, our command comes back and says it's not defined and if you look over in the global environment in the right-hand side, you'll see that the environment is empty. DefinedVector is not defined. So let's fix that. Let's DefinedVector. And we'll put something into it, anything. And now you can see that DefinedVector shows up in the global environment to the right-hand side. Now when we run our command, starting at line two, we get back the message it's already defined. So exists looks in the current environment to see if an object is already existing. Now, an object could be a vector or it could be a function or a matrix or a DataFrame or any R object that you can create. Use exists to save yourself time and to improve the execution speed of your R functions.

内容