Skip to content
This repository has been archived by the owner on Nov 8, 2024. It is now read-only.

enable conversion to sf #8

Merged
merged 1 commit into from
Oct 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions R/mt_subset.R
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,43 @@ mt_subset <- function(product = NULL,
out_dir = out_dir)
}
}

corner_to_coord <- function (x) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This conversion could happen early in mt_subset, to avoid the shifted coordinates.

as.numeric(x) * 1e-5
}

mt_tidy <- function(x) {
tibble::as_tibble(x$header) %>%
dplyr::mutate(data = list(x$data))
}

corner_to_square <- function(x = 0, y = 0, res = c(0.05, 0.05)) {
if (length(x) > 1) {
return(purrr::map2(x, y, .corner_to_square))
}
list(.corner_to_square(x, y, res))
}

.corner_to_square <- function(x = 0, y = 0, res = c(0.05, 0.05)) {
trans <- c(
0, 0,
0, 1,
1, 1,
1, 0,
0, 0
)
matrix(res * trans + c(x, y), 5, 2, byrow = TRUE)
}

to_poly <- function(x) {
x %>%
sf::st_linestring() %>%
sf::st_cast("POLYGON")
}

corner_to_sfc <- function(x, y) {
corner_to_square(x, y) %>%
purrr::map(to_poly) %>%
sf::st_sfc(crs = 4326)
}

49 changes: 49 additions & 0 deletions tests/testthat/test-mt_subset.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
context("test-mt_subset")
library(magrittr)

study_sites <- data.frame(
site_name = paste("test", 1:2),
lat = 40,
lon = -110,
stringsAsFactors = FALSE
)

subsets <- mt_batch_subset(
df = study_sites,
product = "MOD11A2",
band = "LST_Day_1km",
internal = TRUE,
start = "2004-01-01",
end = "2004-02-28",
out_dir = tempdir())

test_that("conversion to `sf` works", {
skip_if_not_installed("sf")
skip_if_not_installed("purrr")
skip_if_not_installed("dplyr")
# single extracts
expect_silent(
subsets %>%
purrr::map_df(mt_tidy) %>%
head(1) %>%
dplyr::mutate(
# these operations could definitely be in `mt_subset`
xc = xllcorner %>% corner_to_coord,
yc = yllcorner %>% corner_to_coord,
geometry = corner_to_sfc(xc, yc)
) %>%
sf::st_as_sf()
)
# multiple extracts
expect_silent(
subsets %>%
purrr::map_df(mt_tidy) %>%
head(2) %>%
dplyr::mutate(
xc = xllcorner %>% corner_to_coord,
yc = yllcorner %>% corner_to_coord,
geometry = corner_to_sfc(xc, yc)
) %>%
sf::st_as_sf()
)
})