There are three ways to calculate the square of a value in R:

**Method 1: Use ^**

x^2

**Method 2: Use ****

x**2

**Method 3: Use ***

x*x

Note that each of these methods will work with a single value, a vector, or a data frame.

The following examples show how to use each method in practice.

**Example1: Calculate Square Using ^**

The following code shows how to calculate the square of a single value using the **^** symbol:

#define variable x <- 5 #calculate square of variable x^2 [1] 25

The following code shows how to calculate the square of each value in a vector using the **^** symbol:

#define vector x <- c(2, 5, 6, 9) #calculate square of each value in vector x^2 [1] 4 25 36 81

The following code shows how to calculate the square of each value in a data frame using the **^** symbol:

#define data frame x <- data.frame(A=c(2, 4, 5, 7, 8), B=c(3, 3, 5, 9, 12), C=c(7, 7, 8, 9, 15)) #view data frame x A B C 1 2 3 7 2 4 3 7 3 5 5 8 4 7 9 9 5 8 12 15 #calculate square of each value in data frame x^2 A B C 1 4 9 49 2 16 9 49 3 25 25 64 4 49 81 81 5 64 144 225

**Example 2: Calculate Square Using ****

The following code shows how to calculate the square of a single value using the ****** symbol:

#define variable x <- 5 #calculate square of variable x**2 [1] 25

The following code shows how to calculate the square of each value in a vector using the ****** symbol:

#define vector x <- c(2, 5, 6, 9) #calculate square of each value in vector x**2 [1] 4 25 36 81

The following code shows how to calculate the square of each value in a data frame using the ****** symbol:

#define data frame x <- data.frame(A=c(2, 4, 5, 7, 8), B=c(3, 3, 5, 9, 12), C=c(7, 7, 8, 9, 15)) #view data frame x A B C 1 2 3 7 2 4 3 7 3 5 5 8 4 7 9 9 5 8 12 15 #calculate square of each value in data frame x**2 A B C 1 4 9 49 2 16 9 49 3 25 25 64 4 49 81 81 5 64 144 225

**Example 3: Calculate Square Using ***

The following code shows how to calculate the square of a single value using the ***** symbol:

#define variable x <- 5 #calculate square of variable x*x [1] 25

The following code shows how to calculate the square of each value in a vector using the ***** symbol:

#define vector x <- c(2, 5, 6, 9) #calculate square of each value in vector x*x [1] 4 25 36 81

The following code shows how to calculate the square of each value in a data frame using the ***** symbol:

#define data frame x <- data.frame(A=c(2, 4, 5, 7, 8), B=c(3, 3, 5, 9, 12), C=c(7, 7, 8, 9, 15)) #view data frame x A B C 1 2 3 7 2 4 3 7 3 5 5 8 4 7 9 9 5 8 12 15 #calculate square of each value in data frame x*x A B C 1 4 9 49 2 16 9 49 3 25 25 64 4 49 81 81 5 64 144 225

Notice that all three methods produce the same result.

Feel free to use whichever method you prefer.

**Additional Resources**

The following tutorials explain how to perform other common tasks in R:

How to Remove Specific Elements from Vector in R

How to Remove NA Values from Vector in R

How to Filter a Vector in R