【发布时间】:2018-12-28 15:00:34
【问题描述】:
我有数百万个 json 文件,其中每个文件都包含相同数量的列,比如 x 和 y。请注意,x 和 y 的长度对于单个文件是相等的,但在比较两个不同文件时可能会有所不同。
问题在于,唯一分隔数据的是文件名。因此,在组合文件时,我希望将文件名包含在第三列中。这是否可能使用sparklyr::spark_read_json,即使用通配符时?
MWE:
library(sparklyr)
## Spark connection
sc <- spark_connect(master = "local", version = "2.1.0")
## Create data
data_dir <- tempdir()
tbl_json1 <- data.frame(x = 1:3, y = 1:3)
tbl_json2 <- data.frame(x = 1:10, y = 1:10)
## Write data to disk
write(jsonlite::toJSON(tbl_json1), sprintf("%s/tab1.json", data_dir))
write(jsonlite::toJSON(tbl_json2), sprintf("%s/tab2.json", data_dir))
## Read both files using wildcard
combined_table <- spark_read_json(
sc,
name = "combined_table",
path = sprintf("%s/*.json", data_dir)
)
## Tranfer results to R
library(dplyr)
dt <- combined_table %>% collect
# # A tibble: 13 x 2
# x y
# <dbl> <dbl>
# 1 1. 1.
# 2 2. 2.
# 3 3. 3.
# 4 4. 4.
# 5 5. 5.
# 6 6. 6.
# 7 7. 7.
# 8 8. 8.
# 9 9. 9.
# 10 10. 10.
# 11 1. 1.
# 12 2. 2.
# 13 3. 3.
想要的输出
# # A tibble: 13 x 2
# x y id
# <dbl> <dbl> <chr>
# 1 1. 1. tab2
# 2 2. 2. tab2
# 3 3. 3. tab2
# 4 4. 4. tab2
# 5 5. 5. tab2
# 6 6. 6. tab2
# 7 7. 7. tab2
# 8 8. 8. tab2
# 9 9. 9. tab2
# 10 10. 10. tab2
# 11 1. 1. tab1
# 12 2. 2. tab1
# 13 3. 3. tab1
【问题讨论】:
标签: r apache-spark dplyr sparklyr