Reputation: 467
I want to make a simple script where I'll sum some variables according to a fixed naming scheme. But the problem is, not all variables will be used every time. But if I try something like this:
result <- sum(variable1, variable2, variable3, na.rm = TRUE)
I get an error saying there's no variable1
. Is there a way to sum only the existing variables and ignore the non-existing ones without declaring all possible variables as NA beforehand?
Upvotes: 0
Views: 208
Reputation: 887511
We could do
Reduce(`+`, mget(ls(pattern = '^variable\\d+$')))
[1] 15
variable2 <- 12
variable3 <- 3
Upvotes: 0
Reputation: 2924
duplicate of this
Add this before:
sapply(c("variable1", "variable2", "variable3"), function(x)
if(!exists(x)) { assign(x, NA, envir=.GlobalEnv) }
)
Upvotes: 1
Reputation: 389135
You can get the variables which are available in the global environment and sum
them.
#Dummy variables
variable2 <- 12
variable3 <- 3
sum(unlist(mget(ls(pattern = 'variable\\d+'))), na.rm = TRUE)
#[1] 15
Upvotes: 3