Skip to content

Added new function condReplace.R#204

Open
bodirsky wants to merge 3 commits intopik-piam:masterfrom
bodirsky:magclass_fork
Open

Added new function condReplace.R#204
bodirsky wants to merge 3 commits intopik-piam:masterfrom
bodirsky:magclass_fork

Conversation

@bodirsky
Copy link
Copy Markdown
Member

@bodirsky bodirsky commented Mar 18, 2026

Currently, the code often includes code like

x[is.na(x)] <- y[is.na(x)]
which is problematic if x any y have a different dimensionality or just a different ordering of the sets or set elements (even if the sets and set elements are identical). This can lead to serious bugs.
The new function replaces this with a safe function, which also integrates conditional statements with lower dimensionality (e.g. conditions over all years or conditions over all regions), as well as replacement with different dimensionality (e.g. partially replacing a country-level dataset with global values).

@bodirsky bodirsky requested a review from codeZeilen March 18, 2026 09:23
Comment thread R/condReplace.R
Comment on lines +26 to +37
condReplace <- function(x, condition, replace) {

if (is.function(condition)) {
replace <- magpie_expand(x = as.magpie(replace), ref = x)
x[condition(x)] <- replace[condition(x)]
} else {
replace <- magpie_expand(x = as.magpie(replace), ref = x)
condition <- magpie_expand(x = as.magpie(condition), ref = x)
x[as.logical(condition)] <- replace[as.logical(condition)]
}
return(x)
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The following removes the redundant applications of the condition function and the conversions to logical. Also pulls out the actual replacement.

Suggested change
condReplace <- function(x, condition, replace) {
if (is.function(condition)) {
replace <- magpie_expand(x = as.magpie(replace), ref = x)
x[condition(x)] <- replace[condition(x)]
} else {
replace <- magpie_expand(x = as.magpie(replace), ref = x)
condition <- magpie_expand(x = as.magpie(condition), ref = x)
x[as.logical(condition)] <- replace[as.logical(condition)]
}
return(x)
}
condReplace <- function(x, condition, replace) {
if (is.function(condition)) {
replace <- magpie_expand(x = as.magpie(replace), ref = x)
condition <- as.logical(condition(x))
} else {
replace <- magpie_expand(x = as.magpie(replace), ref = x)
condition <- as.logical(magpie_expand(x = as.magpie(condition), ref = x))
}
x[condition] <- replace[condition]
return(x)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants