问题: 如何格式化 Terra 包中预测函数的“const”参数?
背景和详细信息:
我正在使用 Terra 的预测函数从模型创建空间 map 。当我为三个常量值创建完整栅格时,该函数按预期工作。当我看到预测有一个常量参数“const”时,我决定使用它。不幸的是,帮助文档没有指定如何构建超出数据框应有的数据结构。
?terra::predict
中“const”的参数描述:
data.frame. Can be used to add a constant value as a predictor variable so that you do not need to make a SpatRaster layer for it
文档底部列出的任何示例中也未使用该参数。
我尝试过的:
我尝试将数据帧格式化为单行,并为模型中所需的每个常量值指定列。该函数接受它并发出警告:
Warning messages: 1: In data.frame(..., check.names = FALSE) : row names were found from a short variable and have been discarded
但这在结果输出中产生了明显不正确的值。可能它只是使用所有三个常量的第一个值,但我不知道。
我还尝试使用两列格式化数据框,一列用于变量名称,一列用于变量值。此操作失败并出现以下错误:
Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'writeRaster': arguments imply differing number of rows: 10000, 3
10000 可能指的是栅格数据的尺寸 (10k x 10k),而 3 可能指的是我提供的常量数据帧中的三行。
我不想回去为每个常量编写栅格,因为我正在生成许多 map ,并且每个 map 都需要使用常量值生成 3 个 10k x 10k 栅格,这非常耗时并且可能会导致内存占用问题。
如有任何建议,我们将不胜感激!
最佳答案
这是一个例子
library(terra)
logo <- rast(system.file("ex/logo.tif", package="terra"))
names(logo) <- c("red", "green", "blue")
p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9, 99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21,37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2)
xy <- rbind(cbind(1, p), cbind(0, a))
e <- extract(logo, xy[,2:3])
v <- data.frame(cbind(pa=xy[,1], e))
model <- glm(formula=pa~., data=v)
names(model$coefficients)[-1]
#[1] "red" "green" "blue"
names(logo)
#[1] "red" "green" "blue"
# standard approach
r <- predict(logo, model)
# one or more constants
r <- predict(logo[[2:3]], model, const=data.frame(red=0))
r <- predict(logo$blue, model, const=data.frame(red=100, green=0))
# you could even use constants only
x <- logo[[1]]
names(x) <- "A"
r <- predict(x, model, const=data.frame(blue=50, red=100, green=0))
输出符合预期:
predict(model, data.frame(blue=50, red=100, green=0))
# 1
#-4.538653
r[1]
# A
#1 -4.538653
关于r - 如何在 Terra::Predict 中格式化 'const' 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71041998/