forked from swcarpentry/r-novice-gapminder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
05-data-structures-part2.Rmd
236 lines (183 loc) · 7.5 KB
/
05-data-structures-part2.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
---
layout: page
title: R for reproducible scientific analysis
subtitle: Exploring Data Frames
minutes: 45
---
```{r, include=FALSE}
source("tools/chunk-options.R")
```
> ## Learning Objectives {.objectives}
>
> - To learn how to manipulate a data.frame in memory
> - To tour some best practices of exploring and understanding a data.frame when it is first loaded.
>
At this point, you've see it all - in the last lesson, we toured all the basic data types and data structures in R. Everything you do will be a manipulation of those tools. But a whole lot of the time, the star of the show is going to be the data.frame - that table that we started with that information from a CSV gets dumped into when we load it. In this lesson, we'll learn a few more things about working with data.frame.
We learned last time that the columns in a data.frame were vectors, so that our data are consistent in type throughout the column. As such, if we want to add a new column, we need to start by making a new vector:
```{r}
newCol <- c(2,3,5,12)
cats
```
We can then add this as a column via:
```{r}
cats <- cbind(cats, newCol)
```
Why didn't this work? Of course, R wants to see one element in our new column for every row in the table:
```{r}
cats
newCol <- c(4,5,8)
cats <- cbind(cats, newCol)
cats
```
Our new column has appeared, but it's got that ugly name at the top; let's give it something a little easier to understand:
```{r}
names(cats)[4] <- 'age'
```
Now how about adding rows - in this case, we saw last time that the rows of a data.frame are made of lists:
```{r}
newRow <- list("tortoiseshell", 3.3, TRUE, 9)
cats <- rbind(cats, newRow)
```
Another thing to look out for has emerged - when R creates a factor, it only allows whatever is originally there when our data was first loaded, which was 'black', 'calico' and 'tabby' in our case. Anything new that doesn't fit into one of its categories is rejected as nonsense, until we explicitly add that as a *level* in the factor:
```{r}
levels(cats$coat)
levels(cats$coat) <- c(levels(cats$coat), 'tortoiseshell')
cats <- rbind(cats, list("tortoiseshell", 3.3, TRUE, 9))
```
Alternatively, we can change a factor column to a character vector; we lose the handy categories of the factor, but can subsequently add any word we want to the column without babysitting the factor levels:
```{r}
str(cats)
cats$coat <- as.character(cats$coat)
str(cats)
```
We now know how to add rows and columns to our data.frame in R - but in our work we've accidentally added a garbage row. We can ask for a data.frame minus this offender:
```{r}
cats[-4,]
```
Notice the comma with nothing after it to indicate we want to drop the entire fourth row.
Alternatively, we can drop all rows with `NA` values:
```{r}
na.omit(cats)
```
In either case, we need to reassign our variable to persist the changes:
```{r}
cats <- na.omit(cats)
```
> ## Discussion 1 {.challenge}
> What do you think
> ```
> cats$weight[4]
> ```
> will print at this point?
>
The key to remember when adding data to a data.frame is that *columns are vectors or factors, and rows are lists.*
We can also glue two dataframes together with `rbind`:
```{r}
cats <- rbind(cats, cats)
cats
```
But now the row names are unnecessarily complicated. We can ask R to re-name everything sequentially:
```{r}
rownames(cats) <- NULL
cats
```
> ### Challenge 1 {.challenge}
>
> You can create a new data.frame right from within R with the following syntax:
> ```{r}
> df <- data.frame(id = c('a', 'b', 'c'), x = 1:3, y = c(TRUE, TRUE, FALSE), stringsAsFactors = FALSE)
> ```
> Make a data.frame that holds the following information for yourself:
>
> - first name
> - last name
> - lucky number
>
> Then use `rbind` to add an entry for the people sitting beside you.
> Finally, use `cbind` to add a column with each person's answer to the question, "Is it time for coffee break?"
>
So far, you've seen the basics of manipulating data.frames with our cat data; now, let's use those skills to digest a more realistic dataset. Lets read in the gapminder dataset that we downloaded previously:
```{r}
gapminder <- read.csv("data/gapminder-FiveYearData.csv")
```
> ## Miscellaneous Tips {.callout}
>
> 1. Another type of file you might encounter are tab-separated
> format. To specify a tab as a separator, use `"\t"`.
>
> 2. You can also read in files from the Internet by replacing
> the file paths with a web address.
>
> 3. You can read directly from excel spreadsheets without
> converting them to plain text first by using the `xlsx` package.
>
Let's investigate gapminder a bit; the first thing we should always do is check out what the data looks like with `str`:
```{r}
str(gapminder)
```
We can also examine individual columns of the data.frame with our `typeof` function:
```{r}
typeof(gapminder$year)
typeof(gapminder$lifeExp)
typeof(gapminder$country)
str(gapminder$country)
```
We can also interrogate the data.frame for information about its dimensions; remembering that `str(gapminder)` said there were 1704 observations of 6 variables in gapminder, what do you think the following will produce, and why?
```{r}
length(gapminder)
```
A fair guess would have been to say that the length of a data.frame would be the number of rows it has (1704), but this is not the case; remember, a data.frame is a *list of vectors and factors*:
```{r}
typeof(gapminder)
```
When `length` gave us 6, it's because gapminder is built out of a list of 6 columns. To get the number of rows and columns in our dataset, try:
```{r}
nrow(gapminder)
ncol(gapminder)
```
Or, both at once:
```{r}
dim(gapminder)
```
We'll also likely want to know what the titles of all the columns are, so we can ask for them later:
```{r}
colnames(gapminder)
```
At this stage, it's important to ask ourselves if the structure R is reporting matches our intuition or expectations; do the basic data types reported for each column make sense? If not, we need to sort any problems out now before they turn into bad surprises down the road, using what we've learned about how R interprets data, and the importance of *strict consistency* in how we record our data.
Once we're happy that the data types and structures seem reasonable, it's time to start digging into our data proper. Check out the first few lines:
```{r}
head(gapminder)
```
To make sure our analysis is reproducible, we should put the code
into a script file so we can come back to it later.
> ## Challenge 2 {.challenge}
>
> Go to file -> new file -> R script, and write an R script
> to load in the gapminder dataset. Put it in the `scripts/`
> directory and add it to version control.
>
> Run the script using the `source` function, using the file path
> as its argument (or by pressing the "source" button in RStudio).
>
> ## Challenge 3 {.challenge}
>
> Read the output of `str(gapminder)` again;
> this time, use what you've learned about factors, lists and vectors,
> as well as the output of functions like `colnames` and `dim`
> to explain what everything that `str` prints out for gapminder means.
> If there are any parts you can't interpret, discuss with your neighbors!
>
## Challenge solutions
> ## Discussion 1 {.challenge}
> Note the difference between row indices, and default row names;
> even though there's no more row named '4',
> cats[4,] is still well-defined (and pointing at the row named '5').
>
> ## Solution to Challenge 1 {.challenge}
> ```{r}
> df <- data.frame(first = c('Grace'), last = c('Hopper'), lucky_number = c(0), stringsAsFactors = FALSE)
> df <- rbind(df, list('Marie', 'Curie', 238) )
> df <- cbind(df, c(TRUE,TRUE))
> names(df)[4] <- 'coffeetime'
> ```
>