0

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?

Jakub Jędrusiak
  • 301
  • 1
  • 12
  • 2
    Why not use a single variable which represents a data structure? Whenever you find yourself using large numbers of variables whose names differ only in an integer suffix, it is a clear sign of a vector /list/dataframe waiting to be born. – John Coleman Aug 26 '21 at 14:30
  • 1
    E.g., `variable <- numeric(); variable[1] <- 1; variable[2] <- -8; sum(variable, na.rm = TRUE)`. "fixed naming scheme" with numbers means you are doing it wrong. – Roland Aug 26 '21 at 14:35
  • @Roland These are just examples, my fixed naming scheme consists of variables J, K, R, JK, JR, KR and JKR. The script divides overall shopping cost between household members – Jakub Jędrusiak Aug 26 '21 at 14:43
  • 1
    That doesn't change anything. Use an appropriate data structure. You can have that naming scheme within the data structure. – Roland Aug 26 '21 at 15:10
  • If you are going to use 7 fixed variables, is it really so hard to initialize them all to NA at the top of the script? That (or an appropriate data structure such as a dataframe) is simply more readable than using the accepted answer. – John Coleman Aug 27 '21 at 10:26
  • @Roland It makes input easier. – Jakub Jędrusiak Aug 28 '21 at 17:20

3 Answers3

3

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

duplicate of this

Add this before:

sapply(c("variable1", "variable2", "variable3"), function(x) 
  if(!exists(x)) { assign(x, NA, envir=.GlobalEnv) } 
)
Quixotic22
  • 2,894
  • 1
  • 6
  • 14
0

We could do

 Reduce(`+`, mget(ls(pattern = '^variable\\d+$')))
[1] 15

data

variable2 <- 12
variable3 <- 3
akrun
  • 874,273
  • 37
  • 540
  • 662