I am a beginner to R. For one of my project I was trying to find the position of stars in R language. The data are available in Gaia data archive and can be downloaded.
Now, the thing is in Python I can import the data directly in Python code (https://astroquery.readthedocs.io/en/latest/gaia/gaia.html), is it possible to do the same in R?
I am currently running this code:
library(httr)
library(jsonlite)
library(xml2)
get_gaia_star_data <- function(star_name) {
# URL encode the star name for use in the query
star_name_encoded <- URLencode(star_name, reserved = TRUE)
# Construct the Gaia TAP query to find the star by name
query <- paste0(
"SELECT TOP 1 source_id, ra, dec ",
"FROM gaiadr2.gaia_source ",
"WHERE CONTAINS(POINT('ICRS', ra, dec), ",
"CIRCLE('ICRS', 0, 0, 180)) = 1 AND ",
"source_id IN (SELECT source_id FROM gaiadr2.gaia_source WHERE ",
"CONTAINS(POINT('ICRS', ra, dec), ",
"CIRCLE('ICRS', ", star_name_encoded, ")) = 1"
)
# URL for the Gaia Archive TAP service
base_url <- "https://gea.esac.esa.int/tap-server/tap"
# Construct the request body
body <- list(
REQUEST = "doQuery",
LANG = "ADQL",
FORMAT = "json",
PHASE = "RUN",
QUERY = query
)
# Perform the query
response <- tryCatch({
POST(paste0(base_url, "/sync"), body = body, encode = "form")
}, error = function(e) {
stop("Failed to connect to Gaia Archive. Error: ", e$message)
})
# Check if the request was successful
if (status_code(response) != 200) {
stop(paste("Failed to query Gaia Archive. HTTP status code:", status_code(response)))
}
# Parse the response content
content <- content(response, "text", encoding = "UTF-8")
data <- tryCatch({
fromJSON(content)
}, error = function(e) {
stop("Failed to parse JSON response.")
})
# Check if the response contains data
if (length(data$data) == 0) {
stop("No results found for the star name.")
}
# Extract RA and Dec from the response
ra <- as.numeric(data$data[[1]]$ra)
dec <- as.numeric(data$data[[1]]$dec)
# Return the coordinates as a list
return(list(
RA = ra,
Dec = dec
))
}
# Example usage
star_name <- "Sirius"
star_location <- get_gaia_star_data(star_name)
print(star_location)
but the HTTP status is 400 no matter what I do.