Reputation: 207
Suppose I have created 3 values in R
brice1 <- 55
brice2 <- 10
brice3 <- brice1 * brice2
I now want to sum all of them.
brice_total <- brice1 + brice2 + brice3
BUT, I don't want to type out every variable. How would I tell R to sum all variables that begin with "Brice". For instance, in STATA a * indicates an ambiguous ending, so I could do something like
egen brice_total = sum(brice*)
I need to do the same thing in R because I need to sum a long list of values that all start with the same string of characters.
Upvotes: 0
Views: 79
Reputation: 887291
We can get values of all the objects with names that starts (^
) with 'brice' followed by one or more digits (\\d+
) till the end of the string ($
) in a list
and Reduce
with +
to get the sum in base R
Reduce(`+`, mget(ls(pattern = '^brice\\d+$')))
Upvotes: 1