课程: R for Data Science: Lunch Break Lessons

Simplify with c

- [Instructor] C will strip out attributes from arrays and data frames and convert them to simple vectors. Sometimes this is exactly what you want. So let's take a look at how C does this and how things behave when you strip out attributes. To demonstrate this, I'm going to need an array so in line two, I create arrayThing and I'm also going to need a data frame so in line three I create something called dfThing. Let's take a look at the... Let's take a look at this array and we'll look at the structure. So I use the str, or structure command, for arrayThing. What you'll see is that I have an array, there are three dimensions, one through 10, one through 10 and one through three. If I list it you can see that I have three levels of that array. Third, second and first. Now I'd like to create one through 300 which is the number of numbers in this array. If I create vectorThing with C, using arrayThing I'll remove all the attributes. Let's use structure to take a look at vectorThing. The first thing you notice is, I no longer have three levels I only have one through 300. vectorThing has become a simple vector with 300 numbers in it. So all of the array attributes have been stripped out. Let's take a look at how it affects data frames. I'm going to run structure against dfThing which is a data frame. And you can see that we have two levels letters, characters a, b, c, d, et cetera and numbers which are ints one, two, three, four, five, six, through 10. In line 11, I'll use C on dfThing and store the result into vectorThing. And now let's take a look at vectorThing. And you can see that I now have a list which is the simplified version of a data frame. Now, maybe I prefer to have a vector from dfThing and I can do that by setting recursive equal true in the C command. I've done just exactly that in line 14. So I'll select line 14, I'll hit run and let's take a look at the resulting vectorThing. And you can see that I know have a named vector. What that means is that if I use vectorThing and then specify an element we'll say letters three in this case I get the third element of the vectorThing which is letters three and it happens to be C. So the important thing to remember here is that C not only combines elements but it also removes the attributes of different elements and gives you a simplified version of the original data object. Whether it's a data frame or a list, or an array.

内容