forked from frictionlessdata/datapackage-r
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathREADME.Rmd
893 lines (621 loc) · 29.3 KB
/
README.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
---
title: <img src="okgr.png" align="right" width=100px /><img src="oklabs.png" align="right" width=100px /><br><br/><br/><img src="Ffrictionless.png" align="left" width=120 /><br/>rictionless Data - <br/>Data Package
output:
github_document:
html_preview: no
number_sections: yes
---
[![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/datapackage.r)](https://cran.r-project.org/package=datapackage.r)
[![R-CMD-check](https://github.com/frictionlessdata/datapackage-r/workflows/R-CMD-check/badge.svg)](https://github.com/frictionlessdata/datapackage-r/actions)
[![Coverage Status](https://coveralls.io/repos/github/frictionlessdata/datapackage-r/badge.svg?branch=master)](https://coveralls.io/github/frictionlessdata/datapackage-r?branch=master)
[![Project Status: Active – The project has reached a stable, usable state but is no longer being actively developed; support/maintenance will be provided as time allows.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active)
[![Rdoc](http://www.rdocumentation.org/badges/version/datapackage.r)](http://www.rdocumentation.org/packages/datapackage.r)
[![](http://cranlogs.r-pkg.org/badges/grand-total/datapackage.r)](http://cran.rstudio.com/web/packages/datapackage.r/index.html)
[![Licence](https://img.shields.io/badge/licence-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Support](https://img.shields.io/badge/support-discord-brightgreen)](https://discordapp.com/invite/Sewv6av)
# Description
R package for working with [Frictionless Data Package][datapackage].
## Features
- `Package` class for working with data packages
- `Resource` class for working with data resources
- `Profile` class for working with profiles
- `validate` function for validating data package descriptors
- `infer` function for inferring data package descriptors
# Getting started
## Installation
In order to install the latest distribution of [R software][Rs] to your computer you have to select one of the mirror sites of the [Comprehensive R Archive Network][R], select the appropriate link for your operating system and follow the wizard instructions.
For windows users you can:
1. Go to CRAN
2. Click download R for Windows
3. Click Base (This is what you want to install R for the first time)
4. Download the latest R version
5. Run installation file and follow the instrustions of the installer.
(Mac) OS X and Linux users may need to follow different steps depending on their system version to install R successfully and it is recommended to read the instructions on CRAN site carefully.
Even more detailed installation instructions can be found in [R Installation and Administration manual][Rman].
To install [RStudio][Rstudio], you can download [RStudio Desktop][Rstudiodown] with Open Source License and follow the wizard instructions:
1. Go to [RStudio](https://www.rstudio.com/products/rstudio/)
2. Click download on RStudio Desktop
3. Download on RStudio Desktop free download
4. Select the appropriate file for your system
5. Run installation file
To install the `datapackage` package it is necessary to install first [devtools package](https://cran.r-project.org/package=devtools) to make installation of github packages available.
```{r, eval=FALSE, include=TRUE}
# Install devtools package if not already
install.packages("devtools")
```
Install `datapackage.r`
```{r, eval=FALSE, include=T}
# And then install the development version from github
devtools::install_github("frictionlessdata/datapackage-r")
```
## Load package
```{r, echo=TRUE}
# load the package using
library(datapackage.r)
```
# Examples
Code examples in this readme requires R 3.3 or higher, You could see even more [examples](https://github.com/frictionlessdata/datapackage-r/tree/master/vignettes) in vignettes directory.
```{r eval=TRUE, include=TRUE, warning=FALSE}
descriptor <- '{
"resources": [
{
"name": "example",
"profile": "tabular-data-resource",
"data": [
["height", "age", "name"],
[180, 18, "Tony"],
[192, 32, "Jacob"]
],
"schema": {
"fields": [
{"name": "height", "type": "integer" },
{"name": "age", "type": "integer" },
{"name": "name", "type": "string" }
]
}
}
]
}'
dataPackage <- Package.load(descriptor)
dataPackage
```
```{r eval=TRUE, include=TRUE, warning=FALSE}
resource <- dataPackage$getResource('example')
# convert to json and add indentation with jsonlite prettify function
jsonlite::prettify(helpers.from.list.to.json(resource$read()))
```
# Documentation
Json objects are not included in R base data types. [Jsonlite package](https://CRAN.R-project.org/package=jsonlite) is internally used to convert json data to list objects. The input parameters of functions could be json strings, files or lists and the outputs are in list format to easily further process your data in R environment and exported as desired. The examples below show how to use jsonlite package to convert the output back to json adding indentation whitespace. More details about handling json you can see jsonlite documentation or vignettes [here](https://CRAN.R-project.org/package=jsonlite).
## Working with Package
A class for working with data packages. It provides various capabilities like loading local or remote data package, inferring a data package descriptor, saving a data package descriptor and many more.
Consider we have some local `csv` files in a `data` directory. Let's create a data package based on this data using a `Package` class:
> inst/extdata/readme_example/cities.csv
```csv
city,location
london,"51.50,-0.11"
paris,"48.85,2.30"
rome,"41.89,12.51"
```
> inst/extdata/readme_example/population.csv
```csv
city,year,population
london,2017,8780000
paris,2017,2240000
rome,2017,2860000
```
```{r "setup", include=FALSE}
require("knitr")
opts_knit$set(root.dir = "inst/extdata/readme_example/")
```
First we create a blank data package:
```{r eval=TRUE, include=TRUE, echo=TRUE}
dataPackage <- Package.load()
```
Now we're ready to infer a data package descriptor based on data files we have. Because we have two csv files we use glob pattern `csv`:
```{r eval=TRUE, include=TRUE, warning=FALSE, message=FALSE}
jsonlite::toJSON(dataPackage$infer('csv'), pretty = TRUE)
```
```{r eval=TRUE, include=TRUE, warning=FALSE, message=FALSE}
jsonlite::toJSON(dataPackage$descriptor, pretty = TRUE)
```
An `infer` method has found all our files and inspected it to extract useful metadata like profile, encoding, format, Table Schema etc. Let's tweak it a little bit:
```{r eval=TRUE, include=TRUE}
dataPackage$descriptor$resources[[2]]$schema$fields[[2]]$type <- 'year'
dataPackage$commit()
dataPackage$valid
```
Because our resources are tabular we could read it as a tabular data:
```{r eval=TRUE, include=TRUE}
jsonlite::toJSON(dataPackage$getResource("population")$read(keyed = TRUE),auto_unbox = FALSE,pretty = TRUE)
```
Let's save our descriptor on the disk. After it we could update our `datapackage.json` as we want, make some changes etc:
```{r eval=FALSE, include=TRUE}
dataPackage.save('datapackage.json')
```
To continue the work with the data package we just load it again but this time using local `datapackage.json`:
```{r eval=FALSE, include=TRUE}
dataPackage <- Package.load('datapackage.json')
# Continue the work
```
It was one basic introduction to the `Package` class. To learn more let's take a look on `Package` class API reference.
### Resource
A class for working with data resources. You can read or iterate tabular resources using the `iter/read` methods and all resource as bytes using `rowIter/rowRead` methods.
Consider we have some local csv file. It could be inline data or remote link - all supported by `Resource` class (except local files for in-brower usage of course). But say it's `cities.csv` for now:
```csv
city,location
london,"51.50,-0.11"
paris,"48.85,2.30"
rome,N/A
```
Let's create and read a resource. We use static `Resource$load` method instantiate a resource. Because resource is tabular we could use `resourceread` method with a `keyed` option to get an list of keyed rows:
```{r eval=TRUE, include=TRUE}
resource <- Resource.load('{"path": "cities.csv"}')
resource$tabular
```
```{r eval=TRUE, include=TRUE}
jsonlite::toJSON(resource$read(keyed = TRUE), pretty = TRUE)
```
As we could see our locations are just a strings. But it should be geopoints. Also Rome's location is not available but it's also just a `N/A` string instead of `null`. First we have to infer resource metadata:
```{r eval=TRUE, include=TRUE}
jsonlite::toJSON(resource$infer(), pretty = TRUE)
```
```{r eval=TRUE, include=TRUE}
jsonlite::toJSON(resource$descriptor, pretty = TRUE)
# resource$read( keyed = TRUE )
# # Fails with a data validation error
```
Let's fix not available location. There is a `missingValues` property in Table Schema specification. As a first try we set `missingValues` to `N/A` in `resource$descriptor.schema`. Resource descriptor could be changed in-place but all changes should be commited by `resource$commit()`:
```{r eval=TRUE, include=TRUE}
resource$descriptor$schema$missingValues <- 'N/A'
resource$commit()
```
```{r eval=TRUE, include=TRUE}
resource$valid # FALSE
resource$errors
```
As a good citiziens we've decided to check out recource descriptor validity. And it's not valid! We should use an list for `missingValues` property. Also don't forget to have an empty string as a missing value:
```{r eval=TRUE, include=TRUE}
resource$descriptor$schema[['missingValues']] <- list('', 'N/A')
resource$commit()
resource$valid # TRUE
```
All good. It looks like we're ready to read our data again:
```{r eval=TRUE, include=TRUE}
jsonlite::toJSON(resource$read( keyed = TRUE ), pretty = TRUE)
```
Now we see that:
- locations are lists with numeric lattide and longitude
- Rome's location is a native JavaScript `null`
And because there are no errors on data reading we could be sure that our data is valid againt our schema. Let's save our resource descriptor:
```{r eval=FALSE, include=TRUE}
resource$save('dataresource.json')
```
Let's check newly-crated `dataresource.json`. It contains path to our data file, inferred metadata and our `missingValues` tweak:
```json
{
"path": "data.csv",
"profile": "tabular-data-resource",
"encoding": "utf-8",
"name": "data",
"format": "csv",
"mediatype": "text/csv",
"schema": {
"fields": [
{
"name": "city",
"type": "string",
"format": "default"
},
{
"name": "location",
"type": "geopoint",
"format": "default"
}
],
"missingValues": [
"",
"N/A"
]
}
}
```
If we decide to improve it even more we could update the `dataresource.json` file and then open it again using local file name:
```{r eval=FALSE, include=TRUE}
resource <- Resource.load('dataresource.json')
# Continue the work
```
It was one basic introduction to the `Resource` class. To learn more let's take a look on `Resource` class API reference.
### Working with Profile
A component to represent JSON Schema profile from [Profiles Registry](https://specs.frictionlessdata.io/schemas/registry.json):
```{r eval=TRUE, include=TRUE}
profile <- Profile.load('data-package')
profile$name # data-package
```
```{r eval=FALSE, include=TRUE}
profile$jsonschema # List of JSON Schema contents
```
```{r eval=TRUE, include=TRUE}
valid_errors <- profile$validate(descriptor)
valid <- valid_errors$valid # TRUE if valid descriptor
valid
```
### Working with validate
A standalone function to validate a data package descriptor:
```{r eval=FALSE, include=TRUE}
valid_errors <- validate('{"name": "Invalid Datapackage"}')
```
### Working with infer
A standalone function to infer a data package descriptor.
```{r eval=TRUE, include=TRUE}
descriptor <- infer("csv",basePath = '.')
jsonlite::toJSON(descriptor, pretty = TRUE)
```
### Working with Foreign Keys
The package supports foreign keys described in the [Table Schema](https://specs.frictionlessdata.io/table-schema/#foreign-keys) specification. It means if your data package descriptor use `resources[]$schema$foreignKeys` property for some resources a data integrity will be checked on reading operations.
Consider we have a data package:
```{r eval=TRUE, include=TRUE}
DESCRIPTOR <- '{
"resources": [
{
"name": "teams",
"data": [
["id", "name", "city"],
["1", "Arsenal", "London"],
["2", "Real", "Madrid"],
["3", "Bayern", "Munich"]
],
"schema": {
"fields": [
{"name": "id", "type": "integer"},
{"name": "name", "type": "string"},
{"name": "city", "type": "string"}
],
"foreignKeys": [
{
"fields": "city",
"reference": {"resource": "cities", "fields": "name"}
}
]
}
}, {
"name": "cities",
"data": [
["name", "country"],
["London", "England"],
["Madrid", "Spain"]
]
}
]
}'
```
Let's check relations for a `teams` resource:
```{r eval=TRUE, include=TRUE, warning=FALSE}
package <- Package.load(DESCRIPTOR)
teams <- package$getResource('teams')
```
```{r eval=TRUE, include=TRUE,warning=FALSE, error=TRUE}
teams$checkRelations()
# tableschema.exceptions.RelationError: Foreign key "['city']" violation in row "4"
```
As we could see there is a foreign key violation. That's because our lookup table `cities` doesn't have a city of `Munich` but we have a team from there. We need to fix it in `cities` resource:
```{r eval=TRUE, include=TRUE}
package$descriptor$resources[[2]]$data <- rlist::list.append(package$descriptor$resources[[2]]$data, list('Munich', 'Germany'))
package$commit()
teams <- package$getResource('teams')
teams$checkRelations()
# TRUE
```
Fixed! But not only a check operation is available. We could use `relations` argument for `resource$iter/read` methods to dereference a resource relations:
```{r eval=TRUE, include=TRUE}
jsonlite::toJSON(teams$read(keyed = TRUE, relations = FALSE), pretty = TRUE)
```
Instead of plain city name we've got a dictionary containing a city data. These `resource$iter/read` methods will fail with the same as `resource$check_relations` error if there is an integrity issue. But only if `relations = TRUE` flag is passed.
## API Referencer
### Package
Package representation
* [Package](#Package)
* _instance_
* [$valid](#Package+valid) ⇒ <code>Boolean</code>
* [$errors](#Package+errors) ⇒ <code>List.<Error></code>
* [$profile](#Package+profile) ⇒ <code>Profile</code>
* [$descriptor](#Package+descriptor) ⇒ <code>Object</code>
* [$resources](#Package+resources) ⇒ <code>List.<Resoruce></code>
* [$resourceNames](#Package+resourceNames) ⇒ <code>List.<string></code>
* [$getResource(name)](#Package+getResource) ⇒ <code>Resource</code> \| <code>null</code>
* [$addResource(descriptor)](#Package+addResource) ⇒ <code>Resource</code>
* [$removeResource(name)](#Package+removeResource) ⇒ <code>Resource</code> \| <code>null</code>
* [$infer(pattern)](#Package+infer) ⇒ <code>Object</code>
* [$commit(strict)](#Package+commit) ⇒ <code>Boolean</code>
* [$save(target, raises, returns)](#Package+save)
* _static_
* [.load(descriptor, basePath, strict)](#Package.load) ⇒ [<code>Package</code>](#Package)
#### package$.valid ⇒ <code>Boolean</code>
Validation status
It always `true` in strict mode.
**Returns**: <code>Boolean</code> - returns validation status
#### package$errors ⇒ <code>List.<Error></code>
Validation errors
It always empty in strict mode.
**Returns**: <code>List.<Error></code> - returns validation errors
#### package$profile ⇒ <code>Profile</code>
Profile
#### package$descriptor ⇒ <code>Object</code>
Descriptor
**Returns**: <code>Object</code> - schema descriptor
#### package$resources ⇒ <code>List.<Resoruce></code>
Resources
#### package$resourceNames ⇒ <code>List.<string></code>
Resource names
#### package$getResource(name) ⇒ <code>Resource</code> \| <code>null</code>
Return a resource
**Returns**: <code>Resource</code> \| <code>null</code> - resource instance if exists
| Param | Type |
| --- | --- |
| name | <code>string</code> |
#### package$addResource(descriptor) ⇒ <code>Resource</code>
Add a resource
**Returns**: <code>Resource</code> - added resource instance
| Param | Type |
| --- | --- |
| descriptor | <code>Object</code> |
#### package$removeResource(name) ⇒ <code>Resource</code> \| <code>null</code>
Remove a resource
**Returns**: <code>Resource</code> \| <code>null</code> - removed resource instance if exists
| Param | Type |
| --- | --- |
| name | <code>string</code> |
#### package$infer(pattern) ⇒ <code>Object</code>
Infer metadata
| Param | Type | Default |
| --- | --- | --- |
| pattern | <code>string</code> | <code>false</code> |
#### package$commit(strict) ⇒ <code>Boolean</code>
Update package instance if there are in-place changes in the descriptor.
**Returns**: <code>Boolean</code> - returns true on success and false if not modified
**Throws**:
- <code>DataPackageError</code> raises any error occurred in the process
| Param | Type | Description |
| --- | --- | --- |
| strict | <code>boolean</code> | alter `strict` mode for further work |
**Example**
```{r eval=TRUE, include=TRUE}
dataPackage <- Package.load('{
"name": "package",
"resources": [{"name": "resource", "data": ["data"]}]
}')
dataPackage$descriptor$name # package
dataPackage$descriptor$name <- 'renamed-package'
dataPackage$descriptor$name # renamed-package
dataPackage$commit()
```
#### package$save(target, raises, returns)
Save data package to target destination.
If target path has a zip file extension the package will be zipped and
saved entirely. If it has a json file extension only the descriptor will be saved.
| Param | Type | Description |
| --- | --- | --- |
| target | <code>string</code> | path where to save a data package |
| raises | <code>DataPackageError</code> | error if something goes wrong |
| returns | <code>boolean</code> | true on success |
#### Package.load(descriptor, basePath, strict) ⇒ [<code>Package</code>](#Package)
Factory method to instantiate `Package` class.
This method is async and it should be used with await keyword or as a `Promise`.
**Returns**: [<code>Package</code>](#Package) - returns data package class instance
**Throws**:
- <code>DataPackageError</code> raises error if something goes wrong
| Param | Type | Description |
| --- | --- | --- |
| descriptor | <code>string</code> \| <code>Object</code> | package descriptor as local path, url or object. If ththe path has a `zip` file extension it will be unzipped to the temp directory first. |
| basePath | <code>string</code> | base path for all relative paths |
| strict | <code>boolean</code> | strict flag to alter validation behavior. Setting it to `true` leads to throwing errors on any operation with invalid descriptor |
### Resource
Resource representation
* [Resource](#Resource)
* _instance_
* [$valid](#Resource+valid) ⇒ <code>Boolean</code>
* [$errors](#Resource+errors) ⇒ <code>List.<Error></code>
* [$profile](#Resource+profile) ⇒ <code>Profile</code>
* [$descriptor](#Resource+descriptor) ⇒ <code>Object</code>
* [$name](#Resource+name) ⇒ <code>string</code>
* [$inline](#Resource+inline) ⇒ <code>boolean</code>
* [$local](#Resource+local) ⇒ <code>boolean</code>
* [$remote](#Resource+remote) ⇒ <code>boolean</code>
* [$multipart](#Resource+multipart) ⇒ <code>boolean</code>
* [$tabular](#Resource+tabular) ⇒ <code>boolean</code>
* [$source](#Resource+source) ⇒ <code>List</code> \| <code>string</code>
* [$headers](#Resource+headers) ⇒ <code>List.<string></code>
* [$schema](#Resource+schema) ⇒ <code>tableschema.Schema</code>
* [$iter(keyed, extended, cast, forceCast, relations, stream)](#Resource+iter) ⇒ <code>AsyncIterator</code> \| <code>Stream</code>
* [$read(limit)](#Resource+read) ⇒ <code>List.<List></code> \| <code>List.<Object></code>
* [$checkRelations()](#Resource+checkRelations) ⇒ <code>boolean</code>
* [$rawIter(stream)](#Resource+rawIter) ⇒ <code>Iterator</code> \| <code>Stream</code>
* [$rawRead()](#Resource+rawRead) ⇒ <code>Buffer</code>
* [$infer()](#Resource+infer) ⇒ <code>Object</code>
* [$commit(strict)](#Resource+commit) ⇒ <code>boolean</code>
* [$save(target)](#Resource+save) ⇒ <code>boolean</code>
* _static_
* [$load(descriptor, basePath, strict)](#Resource.load) ⇒ [<code>Resource</code>](#Resource)
#### resource$valid ⇒ <code>Boolean</code>
Validation status
It always `true` in strict mode.
**Returns**: <code>Boolean</code> - returns validation status
#### resource$errors ⇒ <code>List.<Error></code>
Validation errors
It always empty in strict mode.
**Returns**: <code>List.<Error></code> - returns validation errors
#### resource$profile ⇒ <code>Profile</code>
Profile
#### resource$descriptor ⇒ <code>Object</code>
Descriptor
**Returns**: <code>Object</code> - schema descriptor
#### resource$name ⇒ <code>string</code>
Name
#### resource$inline ⇒ <code>boolean</code>
Whether resource is inline
#### resource$local ⇒ <code>boolean</code>
Whether resource is local
#### resource$remote ⇒ <code>boolean</code>
Whether resource is remote
#### resource$multipart ⇒ <code>boolean</code>
Whether resource is multipart
#### resource$tabular ⇒ <code>boolean</code>
Whether resource is tabular
#### resource$source ⇒ <code>List</code> \| <code>string</code>
Source
Combination of `resource.source` and `resource.inline/local/remote/multipart`
provides predictable interface to work with resource data.
#### resource$headers ⇒ <code>List.<string></code>
Headers
> Only for tabular resources
**Returns**: <code>List.<string></code> - data source headers
#### resource$schema ⇒ <code>tableschema.Schema</code>
Schema
> Only for tabular resources
#### resource$iter(keyed, extended, cast, forceCast, relations, stream) ⇒ <code>AsyncIterator</code> \| <code>Stream</code>
Iterate through the table data
> Only for tabular resources
And emits rows cast based on table schema (async for loop).
With a `stream` flag instead of async iterator a Node stream will be returned.
Data casting can be disabled.
**Returns**: <code>AsyncIterator</code> \| <code>Stream</code> - async iterator/stream of rows:
- `[value1, value2]` - base
- `{header1: value1, header2: value2}` - keyed
- `[rowNumber, [header1, header2], [value1, value2]]` - extended
**Throws**:
- <code>TableSchemaError</code> raises any error occurred in this process
| Param | Type | Description |
| --- | --- | --- |
| keyed | <code>boolean</code> | iter keyed rows |
| extended | <code>boolean</code> | iter extended rows |
| cast | <code>boolean</code> | disable data casting if false |
| forceCast | <code>boolean</code> | instead of raising on the first row with cast error return an error object to replace failed row. It will allow to iterate over the whole data file even if it's not compliant to the schema. Example of output stream: `[['val1', 'val2'], TableSchemaError, ['val3', 'val4'], ...]` |
| relations | <code>boolean</code> | if true foreign key fields will be checked and resolved to its references |
| stream | <code>boolean</code> | return Node Readable Stream of table rows |
#### resource$read(limit) ⇒ <code>List.<List></code> \| <code>List.<Object></code>
Read the table data into memory
> Only for tabular resources; the API is the same as `resource.iter` has except for:
**Returns**: <code>List.<List></code> \| <code>List.<Object></code> - list of rows:
- `[value1, value2]` - base
- `{header1: value1, header2: value2}` - keyed
- `[rowNumber, [header1, header2], [value1, value2]]` - extended
| Param | Type | Description |
| --- | --- | --- |
| limit | <code>integer</code> | limit of rows to read |
#### resource$checkRelations() ⇒ <code>boolean</code>
It checks foreign keys and raises an exception if there are integrity issues.
> Only for tabular resources
**Returns**: <code>boolean</code> - returns True if no issues
**Throws**:
- <code>DataPackageError</code> raises if there are integrity issues
#### resource$rawIter(stream) ⇒ <code>Iterator</code> \| <code>Stream</code>
Iterate over data chunks as bytes. If `stream` is true Node Stream will be returned.
**Returns**: <code>Iterator</code> \| <code>Stream</code> - returns Iterator/Stream
| Param | Type | Description |
| --- | --- | --- |
| stream | <code>boolean</code> | Node Stream will be returned |
#### resource$rawRead() ⇒ <code>Buffer</code>
Returns resource data as bytes.
**Returns**: <code>Buffer</code> - returns Buffer with resource data
#### resource$infer() ⇒ <code>Object</code>
Infer resource metadata like name, format, mediatype, encoding, schema and profile.
It commits this changes into resource instance.
**Returns**: <code>Object</code> - returns resource descriptor
#### resource$commit(strict) ⇒ <code>boolean</code>
Update resource instance if there are in-place changes in the descriptor.
**Returns**: <code>boolean</code> - returns true on success and false if not modified
**Throws**:
- DataPackageError raises error if something goes wrong
| Param | Type | Description |
| --- | --- | --- |
| strict | <code>boolean</code> | alter `strict` mode for further work |
#### resource$save(target) ⇒ <code>boolean</code>
Save resource to target destination.
> For now only descriptor will be saved.
**Returns**: <code>boolean</code> - returns true on success
**Throws**:
- <code>DataPackageError</code> raises error if something goes wrong
| Param | Type | Description |
| --- | --- | --- |
| target | <code>string</code> | path where to save a resource |
#### Resource.load(descriptor, basePath, strict) ⇒ [<code>Resource</code>](#Resource)
Factory method to instantiate `Resource` class.
This method is async and it should be used with await keyword or as a `Promise`.
**Returns**: [<code>Resource</code>](#Resource) - returns resource class instance
**Throws**:
- <code>DataPackageError</code> raises error if something goes wrong
| Param | Type | Description |
| --- | --- | --- |
| descriptor | <code>string</code> \| <code>Object</code> | resource descriptor as local path, url or object |
| basePath | <code>string</code> | base path for all relative paths |
| strict | <code>boolean</code> | strict flag to alter validation behavior. Setting it to `true` leads to throwing errors on any operation with invalid descriptor |
### Profile
Profile representation
* [Profile](#Profile)
* _instance_
* [$name](#Profile+name) ⇒ <code>string</code>
* [$jsonschema](#Profile+jsonschema) ⇒ <code>Object</code>
* [$validate(descriptor)](#Profile+validate) ⇒ <code>Object</code>
* _static_
* [$load(profile)](#Profile.load) ⇒ [<code>Profile</code>](#Profile)
#### profile$name ⇒ <code>string</code>
Name
#### profile$jsonschema ⇒ <code>Object</code>
JsonSchema
#### profile$validate(descriptor) ⇒ <code>Object</code>
Validate a data package `descriptor` against the profile.
**Returns**: <code>Object</code> - returns a `{valid, errors}` object
| Param | Type | Description |
| --- | --- | --- |
| descriptor | <code>Object</code> | retrieved and dereferenced data package descriptor |
#### Profile.load(profile) ⇒ [<code>Profile</code>](#Profile)
Factory method to instantiate `Profile` class.
This method is async and it should be used with await keyword or as a `Promise`.
**Returns**: [<code>Profile</code>](#Profile) - returns profile class instance
**Throws**:
- <code>DataPackageError</code> raises error if something goes wrong
| Param | Type | Description |
| --- | --- | --- |
| profile | <code>string</code> | profile name in registry or URL to JSON Schema |
### validate(descriptor) ⇒ <code>Object</code>
This function is async so it has to be used with `await` keyword or as a `Promise`.
**Returns**: <code>Object</code> - returns a `{valid, errors}` object
| Param | Type | Description |
| --- | --- | --- |
| descriptor | <code>string</code> \| <code>Object</code> | data package descriptor (local/remote path or object) |
### infer(pattern) ⇒ <code>Object</code>
This function is async so it has to be used with `await` keyword or as a `Promise`.
**Returns**: <code>Object</code> - returns data package descriptor
| Param | Type | Description |
| --- | --- | --- |
| pattern | <code>string</code> | glob file pattern |
### DataPackageError
Base class for the all DataPackage errors.
### TableSchemaError
Base class for the all TableSchema errors.
# Contributing
The project follows the [Open Knowledge International coding standards][coding_standards]. There are common commands to work with the project.Recommended way to get started is to create, activate and load the package environment. To install package and development dependencies into active environment:
```{r, eval=FALSE, include=T}
devtools::install_github("frictionlessdata/datapackage-r", dependencies=TRUE)
```
To make test:
```{r, eval=FALSE, include=TRUE}
test_that(description, {
expect_equal(test, expected result)
})
```
To run tests:
```{r, eval=FALSE, include=TRUE, warning=FALSE}
devtools::test()
```
more detailed information about how to create and run tests you can find in [testthat package](https://github.com/hadley/testthat)
## Changelog - News
In [NEWS.md][news] described only breaking and the most important changes. The full changelog could be found in nicely formatted [commit][commits] history.
[Rs]: https://www.r-project.org/
[R]: https://cran.r-project.org//
[Rman]: https://cran.r-project.org/doc/manuals/R-admin.html
[Rstudio]: https://www.rstudio.com/
[Rstudiodown]: https://www.rstudio.com/products/rstudio/download/
[coding_standards]: https://github.com/okfn/coding-standards
[datapackage]: https://specs.frictionlessdata.io/data-package/
[news]: https://github.com/frictionlessdata/datapackage-r/blob/master/NEWS.md
[commits]: https://github.com/frictionlessdata/datapackage-r/commits/master