唯一值的数量

Mou*_*d_S 2 r dplyr apache-spark apache-spark-sql sparklyr

以下示例描述了如何在不使用 dplyr 和 sparklyr 聚合行的情况下计算不同值的数量。

有没有不破坏命令链的解决方法?

更一般地说,如何在 sparklyr 数据帧上使用 sql 之类的窗口函数。

## generating a data set 

set.seed(.328)
df <- data.frame(
  ids = floor(runif(10, 1, 10)),
  cats = sample(letters[1:3], 10, replace = TRUE),
  vals = rnorm(10)
)



## copying to Spark

df.spark <- copy_to(sc, df, "df_spark", overwrite = TRUE)

# Source:   table<df_spark> [?? x 3]
# Database: spark_connection
#   ids  cats       vals
# <dbl> <chr>      <dbl>
#  9     a      0.7635935
#  3     a     -0.7990092
#  4     a     -1.1476570
#  6     c     -0.2894616
#  9     b     -0.2992151
#  2     c     -0.4115108
#  9     b      0.2522234
#  9     c     -0.8919211
#  6     c      0.4356833
#  6     b     -1.2375384
# # ... with more rows

# using the regular dataframe 

df %>% mutate(n_ids = n_distinct(ids))

# ids cats       vals n_ids
# 9    a  0.7635935     5
# 3    a -0.7990092     5
# 4    a -1.1476570     5
# 6    c -0.2894616     5
# 9    b -0.2992151     5
# 2    c -0.4115108     5
# 9    b  0.2522234     5
# 9    c -0.8919211     5
# 6    c  0.4356833     5
# 6    b -1.2375384     5


# using the sparklyr data frame 

df.spark %>% mutate(n_ids = n_distinct(ids))

Error: Window function `distinct()` is not supported by this database
Run Code Online (Sandbox Code Playgroud)

zer*_*323 6

这里最好的方法是单独计算计数,或者使用count? distinct

n_ids <- df.spark %>% 
   select(ids) %>% distinct() %>% count() %>% collect() %>%
   unlist %>% as.vector

df.spark %>% mutate(n_ids = n_ids)
Run Code Online (Sandbox Code Playgroud)

approx_count_distinct

n_ids_approx <- df.spark %>% 
   select(ids) %>% summarise(approx_count_distinct(ids)) %>% collect() %>%
   unlist %>% as.vector

df.spark %>% mutate(n_ids = n_ids_approx)
Run Code Online (Sandbox Code Playgroud)

它有点冗长,但是dplyr如果您想使用全局无界框架,无论如何使用的窗口函数方法都是死胡同。

如果您想要确切的结果,您还可以:

df.spark %>% 
    spark_dataframe() %>% 
    invoke("selectExpr", list("COUNT(DISTINCT ids) as cnt_unique_ids")) %>% 
    sdf_register()
Run Code Online (Sandbox Code Playgroud)

  • 这方面有什么变化吗?sparklyr 没有实现这样一个基本的 sql 函数似乎很奇怪。 (2认同)