r - Bigrquery 强制将字符串强制转换为整数(模式是字符串)
问题描述
我正在使用邮政编码,其中当然有前导零。我正确加载了我的数据框以保留 R 中的前导零,但上传步骤似乎失败了。这就是我的意思:
这是我的 minimum.csv 文件:
zip,val
07030,10
10001,100
90210,1000
60602,10000
这是R代码
require("bigrquery")
filename <- "minimal.csv"
tablename <- "as_STRING"
ds <- bq_dataset(project='myproject', dataset="zips")
我也正确地在我的模式中设置类型以期望它们作为字符串。
# first pass
df <- read.csv(filename, stringsAsFactors=F)
# > df
# zip val
# 1 7030 10
# 2 10001 100
# 3 90210 1000
# 4 60602 10000
# uh oh! Let's fix it!
cols <- unlist(lapply(df, class))
cols[[1]] <- "character" # make zipcode a character
# then reload
df2 <- read.csv(filename, stringsAsFactors=F, colClasses=cols)
# > df2
# zip val
# 1 07030 10
# 2 10001 100
# 3 90210 1000
# 4 60602 10000
# much better! You can see my zips are now strings.
但是,当我尝试上传字符串时,bigrquery 界面抱怨我正在上传整数,但事实并非如此。这是架构,需要字符串:
# create schema
bq_table_create(bq_table(ds, tablename), fields=df2) # using df2, which has strings
# now prove it got the strings right:
> bq_table_meta(bq_table(ds, tablename))$schema$fields
[[1]]
[[1]]$name
[1] "zip"
[[1]]$type
[1] "STRING" # GOOD, ZIP IS A STRING!
[[1]]$mode
[1] "NULLABLE"
[[2]]
[[2]]$name
[1] "val"
[[2]]$type
[1] "INTEGER"
[[2]]$mode
[1] "NULLABLE"
现在是时候上传了......
bq_table_upload(bq_table(ds, tablename), df2) # using df2, with STRINGS
Error: Invalid schema update. Field zip has changed type from STRING to INTEGER [invalid]
嗯?这个无效的架构更新是什么,我怎样才能阻止它尝试将我的字符串(数据包含和架构是)更改为整数,我的数据不包含,架构不包含?
是否正在发生 javascript 序列化并将我的字符串转回整数?
解决方案
这是因为 BigQuery 会在未指定架构时自动检测架构。这可以通过指定fields
参数来解决,如下所示(有关更多详细信息,请参阅此类似问题):
bq_table_upload(bq_table(ds, tablename), df2,fields = list(bq_field("zip", "string"),bq_field("val", "integer")))
更新:
查看代码,bq_table_upload
正在调用bq_perform_upload
,它将参数fields
作为模式。最后,它解析data frame
asJSON
文件以将其上传到 BigQuery。
推荐阅读
- verilog - System Verilog 中的 FileIO 用于浮点数
- python - 仅保留 Pandas Dataframe 中的唯一重复项
- rust - 如何获得 Diesel 架构模块的自动完成功能?
- r - sqldf 中的多个连接,包括完全连接
- url - 使用公共 GitHub API 以 JSON 格式获取所有合并的拉取请求
- proxmox - 无法为容器备份“mkdir /mnt/vzsnap0”,权限被拒绝
- docker - 如何修复“错误:在文件'./docker-compose.yml'中,服务名称True必须是带引号的字符串,即'True'。”
- wordpress - 如何将human_time 应用于get_the_modified_time?
- c# - 修复调用 K8S API 时“无法识别提供给包的凭据”
- shell - 使用自动加载的 ZSH 中的深灰色背景颜色