5 定義資料類型
5.1 簡介
正如前幾章所討論的,Arrow 在讀取資料或將 R 物件轉換為 Arrow 物件時會自動推斷出最適當的資料類型。但是,您可能希望手動告訴 Arrow 要使用哪些資料類型,例如,確保與資料庫和資料倉儲系統的互通性。本章包含以下食譜
- 變更現有 Arrow 物件的資料類型
- 在建立 Arrow 物件的過程中定義資料類型
在 R 資料類型對應 Arrow 資料類型 中可以找到一個顯示 R 和 Arrow 資料類型之間預設對應項的表格。
可以在 Arrow 資料類型對應 R 資料類型 中找到包含 Arrow 資料類型及其 R 對應項的表格。
5.2 更新現有 Arrow 陣列的資料類型
您想要變更既有 Arrow 陣列的資料類型。
5.3 更新現有 Arrow 資料表中欄位的資料類型
您想要變更現有 Arrow 資料表中一個或多個欄位的類型。
5.3.1 解決方案
# Set up a tibble to use in this example
<- tibble::tibble(
oscars actor = c("Katharine Hepburn", "Meryl Streep", "Jack Nicholson"),
num_awards = c(4, 3, 3)
)
# Convert tibble to an Arrow table
<- arrow_table(oscars)
oscars_arrow
# The default mapping from numeric column "num_awards" is to a double
oscars_arrow
## Table
## 3 rows x 2 columns
## $actor <string>
## $num_awards <double>
# Set up schema with "num_awards" as integer
<- schema(actor = string(), num_awards = int16())
oscars_schema
# Cast to an int16
<- oscars_arrow$cast(target_schema = oscars_schema)
oscars_arrow_int
oscars_arrow_int
## Table
## 3 rows x 2 columns
## $actor <string>
## $num_awards <int16>
5.3.2 討論
某些 Arrow 資料類型在 R 中沒有對應的類別。嘗試轉換成這些資料類型或使用包含這些類別的架構,都會導致發生錯誤。
# Set up a tibble to use in this example
<- tibble::tibble(
oscars actor = c("Katharine Hepburn", "Meryl Streep", "Jack Nicholson"),
num_awards = c(4, 3, 3)
)
# Convert tibble to an Arrow table
<- arrow_table(oscars)
oscars_arrow
# Set up schema with "num_awards" as float16 which doesn't have an R equivalent
<- schema(actor = string(), num_awards = float16())
oscars_schema_invalid
# The default mapping from numeric column "num_awards" is to a double
$cast(target_schema = oscars_schema_invalid) oscars_arrow
## Error: NotImplemented: Unsupported cast from double to halffloat using function cast_half_float
5.4 從 R 物件建立 Arrow 資料表時,指定資料類型
您想要在將物件從資料框轉換為 Arrow 物件時,手動指定 Arrow 資料類型。
5.4.1 解決方案
# Set up a tibble to use in this example
<- tibble::tibble(
oscars actor = c("Katharine Hepburn", "Meryl Streep", "Jack Nicholson"),
num_awards = c(4, 3, 3)
)
# Set up schema with "num_awards" as integer
<- schema(actor = string(), num_awards = int16())
oscars_schema
# create arrow Table containing data and schema
<- arrow_table(oscars, schema = oscars_schema)
oscars_data_arrow
oscars_data_arrow
## Table
## 3 rows x 2 columns
## $actor <string>
## $num_awards <int16>
5.5 讀取檔案時,指定資料類型
您想要在讀取檔案時,手動指定 Arrow 資料類型。
5.5.1 解決方案
# Set up a tibble to use in this example
<- tibble::tibble(
oscars actor = c("Katharine Hepburn", "Meryl Streep", "Jack Nicholson"),
num_awards = c(4, 3, 3)
)
# write dataset to disk
write_dataset(oscars, path = "oscars_data")
# Set up schema with "num_awards" as integer
<- schema(actor = string(), num_awards = int16())
oscars_schema
# read the dataset in, using the schema instead of inferring the type automatically
<- open_dataset("oscars_data", schema = oscars_schema)
oscars_dataset_arrow
oscars_dataset_arrow
## FileSystemDataset with 1 Parquet file
## actor: string
## num_awards: int16