You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中使用3x3窗口对含经纬度的栅格执行均值(mean)聚焦操作?

3x3 Focal Operations on Raster Data in R (For Beginners)

Hey there! Since you're new to R and looking to run a 3x3 window (kernel) focal operation on your raster data with latitude/longitude, let's walk through this clearly and simply. We'll use the terra package (the modern successor to the older raster package, which is still usable but less actively maintained) because it's intuitive and efficient for raster work.

Step 1: Install and Load Required Packages

First, make sure you have the terra package installed. If not, run this:

install.packages("terra")
library(terra)

Step 2: Convert Your Data to a Raster Object

If you currently have your data as a data frame with columns for latitude, longitude, and your value (let's call it value), we need to turn this into a raster. Here's how:

# Example data frame (replace this with your actual data)
df <- data.frame(
  lon = seq(-100, -98, by = 0.1),
  lat = seq(30, 32, by = 0.1),
  value = rnorm(length(seq(-100, -98, by = 0.1)))
)

# Convert to raster (xyz = longitude(x), latitude(y), value(z))
r <- rast(df, type = "xyz")

Step 3: Define Your 3x3 Kernel

A 3x3 kernel is a 3x3 matrix that defines how each cell's neighbors are weighted in the focal operation. For a simple moving average (where all 9 cells have equal weight), use:

# 3x3 kernel for equal-weight average
kernel <- matrix(1, nrow = 3, ncol = 3)

If you want a smoother result (like a Gaussian blur), you can use a weighted kernel:

# Gaussian 3x3 kernel (center cell has highest weight)
gaussian_kernel <- matrix(c(1, 2, 1,
                            2, 4, 2,
                            1, 2, 1), nrow = 3, ncol = 3)

Step 4: Run the Focal Operation

Use the focal() function to apply your kernel. Let's start with a simple mean of the 3x3 window:

# Calculate 3x3 focal mean (ignore missing values)
focal_mean <- focal(r, w = kernel, fun = mean, na.rm = TRUE)
  • w = kernel: Specifies your 3x3 window.
  • fun = mean: The function to apply to each window (swap this with sum, max, min, or custom functions!).
  • na.rm = TRUE: Ignores missing values in the window (set to FALSE if you want NA to propagate to results).

Example with a Custom Function

If you want to calculate something specific, like the range (max - min) in each 3x3 window, define a custom function:

range_fun <- function(x) max(x, na.rm = TRUE) - min(x, na.rm = TRUE)
focal_range <- focal(r, w = kernel, fun = range_fun)

Step 5: Visualize the Result

To compare your original data and focal result, plot them side-by-side:

par(mfrow = c(1, 2)) # Set up 1x2 plot layout
plot(r, main = "Original Raster")
plot(focal_mean, main = "3x3 Focal Mean")

Quick Tips for Beginners

  • If you're using the older raster package instead of terra, the workflow is nearly identical—just use raster() instead of rast() and the focal() function from the raster package.
  • Edge cells: By default, focal() returns NA for cells that don't have a full 3x3 window (edge cells). Use the pad argument (e.g., pad = TRUE) to pad edges with NA or a specific value if needed.

内容的提问来源于stack exchange,提问作者Gomal Amin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:16:03