我有一個由緯度(維度 1)和經度(維度 2)坐標組成的二維陣列。每對緯度、經度坐標的位置對應于溫度資料的 3 維陣列中的一個位置(第三維表示深度)。
我想提取經緯度坐標的位置,使得緯度的值為 60<lat<70 和 -60<long<-50,以便我可以將它們與溫度陣列相關聯并提取特定區域的溫度資料。我是 R 新手,一般來說是編程,所以這對我來說是個很大的問題。
#Extracts latitude and longitude matrices into variables
nav_lat <- ncvar_get(nc,"nav_lat")
nav_long <- ncvar_get(nc,"nav_lon")
#Overlays lat and long matrices to create pairs
nav_latlong <- array(c(nav_lat,nav_long),dim=(c(1442,398,2)))
region <- filter(nav_latlong,between(60,70) & between(-60,-50))
這就是你所說的一個可重復的小例子嗎?:
library(tidyverse)
vector_1 <- c(5,9,3)
vector_2 <- c(10,11,12)
result <- array(c(vector_1,vector_2),dim=c(3,3,2))
region <- filter(result,between(result[,,1],5,10) & between(result[,,2],10,12))
所以在這里我想提取第一個元素在 5 到 10 之間,第二個元素在 10 到 12 之間的對。
uj5u.com熱心網友回復:
這是另一種選擇:
#example
set.seed(1)
lat <- matrix(runif(9, 50, 80), nrow = 3)
long <- matrix(runif(9, -70, -50), nrow = 3)
latlong <- array(c(lat, long), dim = c(3,3,2))
latlong
#> , , 1
#>
#> [,1] [,2] [,3]
#> [1,] 57.96526 77.24623 78.34026
#> [2,] 61.16372 56.05046 69.82393
#> [3,] 67.18560 76.95169 68.87342
#>
#> , , 2
#>
#> [,1] [,2] [,3]
#> [1,] -68.76427 -56.25954 -60.04602
#> [2,] -65.88051 -62.31793 -55.64763
#> [3,] -66.46886 -54.60317 -50.16188
#create filter mask
mask <- array(dim = c(3,3,2))
mask[,,1] <- dplyr::between(latlong[,,1], 60, 70)
mask[,,2] <- dplyr::between(latlong[,,2], -60, -50)
mask <- mask[,,1] & mask[,,2]
mask
#> [,1] [,2] [,3]
#> [1,] FALSE FALSE FALSE
#> [2,] FALSE FALSE TRUE
#> [3,] FALSE FALSE TRUE
#apply mask to get lat long pairs
apply(latlong, 3, \(x) x[mask])
#> [,1] [,2]
#> [1,] 69.82393 -55.64763
#> [2,] 68.87342 -50.16188
編輯提取溫度
如果您想知道原始陣列中 lat long 的索引,可以使用which(mask, arr.ind = TRUE). 您不需要mask == TRUE,因為mask已經是合乎邏輯的(即 TRUE 和 FALSE 的矩陣)。或者,您可以將掩碼應用于您的溫度矩陣(假設它是相同的尺寸)。見下文。
#temperature example
set.seed(32)
temperatures <- matrix(runif(9, -20, 20), nrow = 3)
temperatures
#> [,1] [,2] [,3]
#> [1,] 0.2336209 9.152789 10.141508
#> [2,] 3.7923355 -13.920497 14.082492
#> [3,] 12.3498853 18.247490 6.937671
#get the temperatures
temperatures[mask]
#> [1] 14.082492 6.937671
或者更好的方法是將溫度添加到 lat long 陣列并立即提取所有內容,這樣您就有了很好的資料輸出:
all_data <- abind::abind(latlong, temperatures, along = 3)
all_data
#> , , 1
#>
#> [,1] [,2] [,3]
#> [1,] 57.96526 77.24623 78.34026
#> [2,] 61.16372 56.05046 69.82393
#> [3,] 67.18560 76.95169 68.87342
#>
#> , , 2
#>
#> [,1] [,2] [,3]
#> [1,] -68.76427 -56.25954 -60.04602
#> [2,] -65.88051 -62.31793 -55.64763
#> [3,] -66.46886 -54.60317 -50.16188
#>
#> , , 3
#>
#> [,1] [,2] [,3]
#> [1,] 0.2336209 9.152789 10.141508
#> [2,] 3.7923355 -13.920497 14.082492
#> [3,] 12.3498853 18.247490 6.937671
#get lat long and temperature
apply(all_data, 3, \(x) x[mask]) |>
`colnames<-`(c("Lat", "Long", "Temperature"))
#> Lat Long Temperature
#> [1,] 69.82393 -55.64763 14.082492
#> [2,] 68.87342 -50.16188 6.937671
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525519.html
標籤:r数组筛选片
下一篇:使用權重創建堆疊密度圖
