xiaodai
xiaodai

Reputation: 16064

How to row bind two Spark dataframes using sparklyr?

I tried the following to row bind two Spark dataframes but I gave an error message

library(sparklyr)
library(dplyr)
sc <- spark_connect(master = "local")
iris_tbl <- copy_to(sc, iris)
iris_tbl1 <- copy_to(sc, iris, "iris1")

iris_tbl2 = bind_rows(iris_tbl, iris_tbl1)

What's the most efficient way to bind two Spark dataframes together?

Upvotes: 4

Views: 2679

Answers (1)

zero323
zero323

Reputation: 330423

You can use dplyr::union_all

dplyr::union_all(iris_tbl1, iris_tbl1)

or sparklyr::sdf_bind_rows:

sdf_bind_rows(
  iris_tbl %>% select(-Sepal_Length),
  iris_tbl1 %>% select(-Petal_Length)
)

You could also use Spark's own unionByName if schemas are compatible, but the order of columns doesn't match.

sdf_union_by_name <- function(x, y) {
  invoke(spark_dataframe(x), "unionByName", spark_dataframe(y)) %>% 
    sdf_register()
}

sdf_union_by_name(
  iris_tbl %>% select(Sepal_Length, Petal_Length),
  iris_tbl %>% select(Petal_Length, Sepal_Length)
)

Upvotes: 6

Related Questions