# ตัวอย่างใช้ Open API ของศูนย์ข้อมูลเกษตรแห่งชาติ (NABC) ด้วยภาษา R # ไม่ต้องสมัคร ไม่ต้องใช้คีย์ · 60 ครั้ง/นาที/IP · โปรดระบุแหล่งที่มาตามช่อง meta$attribution # คู่มือ: https://nabc.go.th/open-api/china-fruit-prices · https://nabc.go.th/open-api/fertilizer-trade # ติดตั้งครั้งแรก: install.packages(c("jsonlite", "ggplot2")) library(jsonlite) BASE <- "https://nabc.go.th/api/open/v1" nabc_get <- function(path, ...) { q <- list(...) qs <- if (length(q)) paste0("?", paste(names(q), vapply(q, function(v) URLencode(as.character(v), reserved = TRUE), ""), sep = "=", collapse = "&")) else "" fromJSON(paste0(BASE, "/", path, qs)) } # 1) การนำเข้า-ส่งออกปุ๋ยรายปี (is_partial = TRUE คือยอดสะสมยังไม่ครบปี) yearly <- nabc_get("fertilizer-trade/yearly") cat(yearly$meta$attribution, "\n") full <- subset(yearly$data, !is_partial) print(full[order(full$year_be), c("year_be", "import_ton", "export_ton", "balance_baht")]) # 2) ราคาทุเรียนในตลาดจีนรายเดือน แยกประเทศแหล่งผลิต (ใช้เดือนที่มีอย่างน้อย 3 ราคา) m <- nabc_get("china-fruit-prices/monthly", fruit = "durian")$data m <- subset(m, n_prices >= 3) library(ggplot2) ggplot(m, aes(x = month, y = median_cny_per_kg, colour = origin_en, group = origin_en)) + geom_line() + geom_point() + labs(title = "Durian retail price in Chinese markets (median, CNY/kg)", x = NULL, y = "CNY/kg", colour = "Origin") + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 3) อ่านเป็น CSV โดยตรง csv <- read.csv(paste0(BASE, "/fertilizer-trade/yearly?format=csv"), fileEncoding = "UTF-8-BOM") head(csv)