開始使用免費開始

可折疊運算(I)

如果一個運算,同時套用在整個資料集,或先套用在資料集的分塊再把各分塊的結果合併,得到的答案都一樣,這類運算有時稱為「可折疊」(foldable)。max()min() 就是這樣的例子。 這裡我們定義了一個可折疊版本的 range() 函式,可接受向量或向量的 list。 請在房貸資料集上測試,確認這個函式可正常運作。

本練習屬於課程

R 的可擴展資料處理

檢視課程

練習說明

  • 驗證 foldable_range() 能在 mort 資料集的 "record_number" 欄位上運作。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

foldable_range <- function(x) {
  if (is.list(x)) {
    # If x is a list then reduce it by the min and max of each element in the list
    c(Reduce(min, x), Reduce(max, x))
  } else {
    # Otherwise, assume it's a vector and find its range
    range(x)
  }
}

# Verify that foldable_range() works on the record_number column
___
編輯並執行程式碼