如何在 R 中自动进行变量替换?
How to automate variable replacement in R?
我正在使用 R 中的 scPDSI
包为大约 8000 个站点生成干旱指数。我有从 1994 年到 2018 年的月度数据。我的每个站点在 csv 文件中都有自己的列。例如,对于我的第一个站点,我有降水 (P1
) 和潜在蒸发 (PE1
)。使用 scPDSI
包,我只需编写以下内容:
Index <- pdsi(Drought$P1, Drought$PE1, start = 1994, end = 2018, sc=TRUE)
它会计算我的第一个站点的干旱指数。
如何让 R 为每个站点生成索引,而不必为 P2
(resp. PE2
)替换 P1
(和 PE1
)和然后 P3
(PE3
),等等等等手动?这可能吗?
也许像下面的代码这样的东西可以解决问题。未经测试,因为没有数据。
library(scPDSI)
fun <- function(x, y, data, start, end, sc){
X <- data[[x]]
Y <- data[[y]]
pdsi(X, Y, start = start, end = end, sc = sc)
}
other_args_list <- list(
data = Drought,
start = 1994,
end = 2018,
sc = TRUE
)
Pcols <- grep("^P\d+$", names(Drought), value = TRUE)
PEcols <- grep("^PE\d+$", names(Drought), value = TRUE)
Index_vec <- mapply(fun, Pcols, PEcols, MoreArgs = other_args_list)
我正在使用 R 中的 scPDSI
包为大约 8000 个站点生成干旱指数。我有从 1994 年到 2018 年的月度数据。我的每个站点在 csv 文件中都有自己的列。例如,对于我的第一个站点,我有降水 (P1
) 和潜在蒸发 (PE1
)。使用 scPDSI
包,我只需编写以下内容:
Index <- pdsi(Drought$P1, Drought$PE1, start = 1994, end = 2018, sc=TRUE)
它会计算我的第一个站点的干旱指数。
如何让 R 为每个站点生成索引,而不必为 P2
(resp. PE2
)替换 P1
(和 PE1
)和然后 P3
(PE3
),等等等等手动?这可能吗?
也许像下面的代码这样的东西可以解决问题。未经测试,因为没有数据。
library(scPDSI)
fun <- function(x, y, data, start, end, sc){
X <- data[[x]]
Y <- data[[y]]
pdsi(X, Y, start = start, end = end, sc = sc)
}
other_args_list <- list(
data = Drought,
start = 1994,
end = 2018,
sc = TRUE
)
Pcols <- grep("^P\d+$", names(Drought), value = TRUE)
PEcols <- grep("^PE\d+$", names(Drought), value = TRUE)
Index_vec <- mapply(fun, Pcols, PEcols, MoreArgs = other_args_list)