Skip to main content
2 of 5
added 10 characters in body

#R 3.3.2: 209 196 bytes

The idea is to "misuse" the non-arithmetic operators <, &, |, ~, ? where we know the precedence (see ?Syntax in R - but before the override ;)) and overriding them with the given arithmetic operators. The mapping is according to the desired order of operations.

Spaces and commas in the input are not supported.

Golfed version

f=function(a,b){s=substr;l=list('E'='^','M'='*','D'='/','A'='+','S'='-');q="<&|~?";for(i in 1:5){x=s(q,i,i);y=l[[s(a,i,i)]];assign(x,.Primitive(y));b=gsub(paste0('\\',y),x,b)};eval(parse(text=b))}

Ungolfed and commented:

f = function(a,b) {
  s = substr
  # All arithmetic operators
  l = list('E'='^', 'M'='*', 'D'='/', 'A'='+', 'S'='-')
  # Some non-arithmetic R operators in descending precedence
  q = "<&|~?"
  for (i in 1:5) {
    # The substituted symbol
    x = s(q, i, i)
    # The original operator which has to be substituted
    y = l[[s(a, i, i)]]
    # Substitute the operator for the R interpreter
    assign(x, .Primitive(y))
    # Substitute the operator in the input string
    b = gsub(paste0('\\', y), x, b)
  }
  # Parse and evaluate
  eval(parse(text = b))
}

Examples:

> f("EMDAS", "3+6*2/4-1")
[1] 5
> f("DAMES", "3+6*2/4-1")
[1] 3.5
> f("SADME", "3+6*2/4-1")
[1] 6
> f("MEADS", "3+5^4/2-3*2")
[1] 308
> f("AMEDS", "4*3-sin(0.5^2)*3+1")
[1] 11.01038
> f("DAMES", "4-5-6")
[1] -7