@@ -207,14 +207,16 @@ data_files = list.files(pattern = "locations-")
207
207
* First create an empty vector to store those counts
208
208
209
209
``` r
210
- results <- vector(mode = " integer" , length = length(data_files ))
210
+ n_files = length(data_files )
211
+ results <- integer(n_files )
211
212
```
212
213
213
214
* Then write our loop
214
215
215
216
``` r
216
- for (i in 1 : length(data_files ){
217
- data <- read.csv(data_files [i ])
217
+ for (i in 1 : n_files ){
218
+ filename <- data_files [i ]
219
+ data <- read.csv(filename )
218
220
count <- nrow(data )
219
221
results [i ] <- count
220
222
}
@@ -228,38 +230,31 @@ for (i in 1:length(data_files){
228
230
* We often want to calculate multiple pieces of information in a loop making it useful to store results in things other than vectors
229
231
* We can store them in a data frame instead by creating an empty data frame and storing the results in the ` i ` th row of the appropriate column
230
232
* Associate the file name with the count
233
+ * Also store the minimum latitude
231
234
* Start by creating an empty data frame
232
235
* Use the ` data.frame ` function
233
236
* Provide one argument for each column
234
237
* "Column Name" = "an empty vector of the correct type"
235
238
236
239
``` r
237
- results <- data.frame (file_name = vector(mode = " character" , length = length(data_files )))
238
- count = vector(mode = " integer" , length = length(data_files )))
240
+ results <- data.frame (file_name = character (n_files ),
241
+ count = integer(n_files ),
242
+ min_lat = numeric (n_files ))
239
243
```
240
244
241
245
* Now let's modify our loop from last time
242
246
* Instead of storing ` count ` in ` results[i] ` we need to first specify the ` count ` column using the ` $ ` : ` results$count[i] `
243
247
* We also want to store the filename, which is ` data_files[i] `
244
248
245
249
``` r
246
- for (i in 1 : length(data_files ){
247
- data <- read.csv(data_files [i ])
248
- count <- nrow(data )
249
- results $ file_name [i ] <- data_files [i ]
250
- results $ count [i ] <- count
251
- }
252
- ```
253
-
254
- * We could also rewrite this a little to make it easier to understand by getting the file name at the begging
255
-
256
- ``` r
257
- for (i in 1 : length(data_files ){
250
+ for (i in 1 : n_files ){
258
251
filename <- data_files [i ]
259
252
data <- read.csv(filename )
260
253
count <- nrow(data )
254
+ min_lat = min(data $ lat )
261
255
results $ file_name [i ] <- filename
262
256
results $ count [i ] <- count
257
+ results $ min_lat [i ] <- min_lat
263
258
}
264
259
```
265
260
0 commit comments