Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise to power in R

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)?

like image 642
Nick Avatar asked May 05 '15 03:05

Nick


People also ask

How do you raise to a power in R?

In R, for the calculation of power we can simply use power operator ^ and this will be also used in case of generating a power sequence. For example, if we want to generate a power sequence from 1 to 5 of 2 then we can use the code 2^(1:5) this will result 2 4 8 16 32.

What is 1 raise to the power?

Answer: Anything to the power of 1 equals the number itself. Let's solve this question step by step. Explanation: According to the exponent rule, any number raised to the power of one equals the number itself.


1 Answers

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 
like image 104
IRTFM Avatar answered Oct 06 '22 18:10

IRTFM