Mag*_*gie 4 r data-science sparklyr
我试图在sparklyr中使用group_by()和mutate()函数来连接组中的行.
这是一个我认为应该有效的简单示例,但不是:
library(sparkylr)
d <- data.frame(id=c("1", "1", "2", "2", "1", "2"),
x=c("200", "200", "200", "201", "201", "201"),
y=c("This", "That", "The", "Other", "End", "End"))
d_sdf <- copy_to(sc, d, "d")
d_sdf %>% group_by(id, x) %>% mutate( y = paste(y, collapse = " "))
Run Code Online (Sandbox Code Playgroud)
我想要它产生的是:
Source: local data frame [6 x 3]
Groups: id, x [4]
# A tibble: 6 x 3
id x y
<fctr> <fctr> <chr>
1 1 200 This That
2 1 200 This That
3 2 200 The
4 2 201 Other End
5 1 201 End
6 2 201 Other End
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Error: org.apache.spark.sql.AnalysisException: missing ) at 'AS' near '' '' in selection target; line 1 pos 42
Run Code Online (Sandbox Code Playgroud)
请注意,在data.frame上使用相同的代码可以正常工作:
d %>% group_by(id, x) %>% mutate( y = paste(y, collapse = " "))
Run Code Online (Sandbox Code Playgroud)
小智 8
Spark sql如果您在没有聚合的情况下使用聚合函数,那么它就不喜欢它了,因此这个函数在dplyr普通函数中工作dataframe但不在函数中SparkDataFrame- sparklyr将命令转换为sql语句.如果您查看错误消息中的第二位,您可以观察到这种错误:
== SQL ==
SELECT `id`, `x`, CONCAT_WS(' ', `y`, ' ' AS "collapse") AS `y`
Run Code Online (Sandbox Code Playgroud)
paste被翻译成CONCAT_WS.concat但是会将列粘贴在一起.
一个更好的等价会collect_list和collect_set,但它们产生list的输出.
但你可以建立在:
如果你不希望有同一行中的结果复制就可以使用summarise,collect_list以及paste:
res <- d_sdf %>%
group_by(id, x) %>%
summarise( yconcat =paste(collect_list(y)))
Run Code Online (Sandbox Code Playgroud)
结果:
Source: lazy query [?? x 3]
Database: spark connection master=local[8] app=sparklyr local=TRUE
Grouped by: id
id x y
<chr> <chr> <chr>
1 1 201 End
2 2 201 Other End
3 1 200 This That
4 2 200 The
Run Code Online (Sandbox Code Playgroud)
你可以加入这个返回到原来的数据,如果你不希望你的行复制:
d_sdf %>% left_join(res)
Run Code Online (Sandbox Code Playgroud)
结果:
Source: lazy query [?? x 4]
Database: spark connection master=local[8] app=sparklyr local=TRUE
id x y yconcat
<chr> <chr> <chr> <chr>
1 1 200 This This That
2 1 200 That This That
3 2 200 The The
4 2 201 Other Other End
5 1 201 End End
6 2 201 End Other End
Run Code Online (Sandbox Code Playgroud)