61

This is a beginner's question.

  1. What's the difference between ^ and **? For example:

    2 ^ 10
    
    [1] 1024
    
    2 ** 10
    
    [1] 1024
    
  2. Is there a function such as power(x,y)?

seaotternerd
  • 6,298
  • 2
  • 47
  • 58
Nick
  • 8,451
  • 13
  • 57
  • 106
  • 14
    `?'**'` :`** is translated in the parser to ^` – rawr May 05 '15 at 03:52
  • 1
    @rawr Thank you. I should have read the whole page of the documentation. It says: `** is translated in the parser to ^, but this was undocumented for many years. ...` – Nick May 05 '15 at 03:56
  • 6
    Entering `**` at the command line also gives `Error: unexpected '^' in "**"` – thelatemail May 05 '15 at 03:57
  • For anyone younger than about 50, old timers are used to this operator from Fortran. Since R uses alot of Fortran code internally, this isnt going anywhere. – Kostas Feb 21 '23 at 18:50

1 Answers1

58

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math?Arithmetic

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 1
    Wow, the function with prefix notation is a little surprise! Thank you! – Nick May 05 '15 at 03:57
  • 2
    Agree, that is a surprise. `is.function(` ``**``` `) # Error: object '**' not found` (there were backticks inside those parentheses.) – IRTFM May 05 '15 at 04:25
  • Yesterday morning my wife asked me what the caret (`^`) meant in an expression, but then she was still puzzled because it was part of a crossword clue: "Like 8^2 and 4^3". The answer was "equals" which she derived from me talking about prime factors and noting they were both 2^6. – IRTFM Feb 27 '19 at 03:09
  • 1
    The note is not under `?Math` anymore but under `?\`**\``, `?Arithmetic` or `?\`^\``: "** is translated in the parser to ^, but this was undocumented for many years. It appears as an index entry in Becker et al (1988), pointing to the help for Deprecated but is not actually mentioned on that page. Even though it had been deprecated in S for 20 years, it was still accepted in R in 2008." This is also the power operator in python. – Paul Rougieux Apr 17 '20 at 07:01
  • Still accepted by parser in late 2022. – IRTFM Dec 23 '22 at 00:20