當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R SparkR gapplyCollect用法及代碼示例

說明:

使用指定的列對 SparkDataFrame 進行分組,將 R 函數應用於每個組,並將結果作為 data.frame 收集回 R。

用法:

gapplyCollect(x, ...)

## S4 method for signature 'GroupedData'
gapplyCollect(x, func)

## S4 method for signature 'SparkDataFrame'
gapplyCollect(x, cols, func)

參數:

  • x SparkDataFrame 或 GroupedData。
  • ... 傳遞給方法的附加參數。
  • func 要應用於由 SparkDataFrame 的分組列指定的每個組分區的函數。查看詳細信息。
  • cols 分組列。

細節:

func 是兩個參數的函數。第一個,通常命名為key(盡管這不是強製的)對應於分組鍵,將是一個未命名的length(cols) length-one 對象的list,對應於當前組的分組列的值。

第二個,這裏是 x ,將是一個本地的 data.frame ,對於與 key 對應的行,輸入的列不在 cols 中。

func 的輸出必須是與 schema 匹配的 data.frame - 特別是這意味著輸出 data.frame 的名稱無關緊要

返回:

一個 DataFrame 。

注意:

自 2.0.0 以來的 gapplyCollect(GroupedData)

從 2.0.0 開始的 gapplyCollect(SparkDataFrame)

例子:

# Computes the arithmetic mean of the second column by grouping
# on the first and third columns. Output the grouping values and the average.

df <- createDataFrame (
list(list(1L, 1, "1", 0.1), list(1L, 2, "1", 0.2), list(3L, 3, "3", 0.3)),
  c("a", "b", "c", "d"))

result <- gapplyCollect(
  df,
  c("a", "c"),
  function(key, x) {
    y <- data.frame(key, mean(x$b), stringsAsFactors = FALSE)
    colnames(y) <- c("key_a", "key_c", "mean_b")
    y
  })

# We can also group the data and afterwards call gapply on GroupedData.
# For example:
gdf <- group_by(df, "a", "c")
result <- gapplyCollect(
  gdf,
  function(key, x) {
    y <- data.frame(key, mean(x$b), stringsAsFactors = FALSE)
    colnames(y) <- c("key_a", "key_c", "mean_b")
    y
  })

# Result
# ------
# key_a key_c mean_b
# 3 3 3.0
# 1 1 1.5

# Fits linear models on iris dataset by grouping on the 'Species' column and
# using 'Sepal_Length' as a target variable, 'Sepal_Width', 'Petal_Length'
# and 'Petal_Width' as training features.

df <- createDataFrame (iris)
result <- gapplyCollect(
  df,
  df$"Species",
  function(key, x) {
    m <- suppressWarnings(lm(Sepal_Length ~
    Sepal_Width + Petal_Length + Petal_Width, x))
    data.frame(t(coef(m)))
  })

# Result
# ---------
# Model  X.Intercept.  Sepal_Width  Petal_Length  Petal_Width
# 1        0.699883    0.3303370    0.9455356    -0.1697527
# 2        1.895540    0.3868576    0.9083370    -0.6792238
# 3        2.351890    0.6548350    0.2375602     0.2521257

相關用法


注:本文由純淨天空篩選整理自spark.apache.org大神的英文原創作品 gapplyCollect。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。