跳到內容

本文描述 arrow 提供的各種資料和 metadata 物件類型,並記錄這些物件的結構。

Arrow metadata 類別

arrow 套件定義了以下類別來表示 metadata

  • SchemaField 物件的列表,用於描述表格資料物件的結構;其中
  • Field 指定字串名稱和 DataType;以及
  • DataType 是一種屬性,用於控制值的表示方式

考慮以下情況

df <- data.frame(x = 1:3, y = c("a", "b", "c"))
tb <- arrow_table(df)
tb$schema
## Schema
## x: int32
## y: string
## 
## See $metadata for additional Schema metadata

自動推斷的 schema 也可以手動建立

schema(
  field(name = "x", type = int32()),
  field(name = "y", type = utf8())
)
## Schema
## x: int32
## y: string

schema() 函數允許使用以下簡寫方式來定義欄位

schema(x = int32(), y = utf8())
## Schema
## x: int32
## y: string

有時手動指定 schema 很重要,特別是如果您想要精細控制 Arrow 資料類型

arrow_table(df, schema = schema(x = int64(), y = utf8()))
## Table
## 3 rows x 2 columns
## $x <int64>
## $y <string>
## 
## See $metadata for additional Schema metadata
arrow_table(df, schema = schema(x = float64(), y = utf8()))
## Table
## 3 rows x 2 columns
## $x <double>
## $y <string>
## 
## See $metadata for additional Schema metadata

R 物件屬性

Arrow 支援附加到 Schema 的自訂鍵值 metadata。當我們將 data.frame 轉換為 Arrow Table 或 RecordBatch 時,套件會將附加到 data.frame 欄位的任何 attributes() 儲存在 Arrow 物件 Schema 中。以這種方式添加到物件的屬性會儲存在 r 鍵下,如下所示

# data frame with custom metadata
df <- data.frame(x = 1:3, y = c("a", "b", "c"))
attr(df, "df_meta") <- "custom data frame metadata"
attr(df$y, "col_meta") <- "custom column metadata"

# when converted to a Table, the metadata is preserved
tb <- arrow_table(df)
tb$metadata
## $r
## $r$attributes
## $r$attributes$df_meta
## [1] "custom data frame metadata"
## 
## 
## $r$columns
## $r$columns$x
## NULL
## 
## $r$columns$y
## $r$columns$y$attributes
## $r$columns$y$attributes$col_meta
## [1] "custom column metadata"
## 
## 
## $r$columns$y$columns
## NULL

也可以使用類似這樣的命令,在您希望的任何其他鍵下分配額外的字串 metadata

tb$metadata$new_key <- "new value"

當將 Table 寫入 Arrow/Feather 或 Parquet 格式時,附加到 Schema 的 Metadata 會被保留。當將這些檔案讀取到 R 中,或在 Table 或 RecordBatch 上呼叫 as.data.frame() 時,欄位屬性會還原到產生的 data.frame 的欄位。這表示自訂資料類型,包括 haven::labelledvctrs 註釋和其他類型,在透過 Arrow 進行往返時都會被保留。

請注意,儲存在 $metadata$r 中的屬性僅 R 能理解。如果您將具有 haven 欄位的 data.frame 寫入 Feather 檔案,並在 Pandas 中讀取該檔案,則 haven metadata 將無法在那裡被識別。同樣地,Pandas 會寫入自己的自訂 metadata,而 R 套件不會使用。但是,您可以自由地為您的應用程式定義自訂 metadata 慣例,並將您想要的任何(字串)值分配給其他 metadata 鍵。

延伸閱讀

  • 若要進一步了解 arrow metadata,請參閱 schema() 的文件。
  • 若要進一步了解資料類型,請參閱資料類型文章