Calculate Square in R

Square in R, In this tutorial, will describe how to calculate the values of a data points to the power of two in R.

We are going to cover the following cases,

1)     Square of a single value in R

2)     Square of Vector in R

3)     Square of the data frame in R

Linear Discriminant Analysis in R » LDA Prediction »

Example 1:- Single Value Square in R

Square of Single Value, Let’s store the value in x.

x <- 10                            
x   
[1] 10

Now we stored value 10 in x, let’s calculate the power of x using the ^ symbol

x^2  
[1] 100

In another way, can calculate based on the * symbol

x**2
[1] 100

or

x*x
[1] 100

Example 2:-

Square of a vector, Let’s create a vector and calculate a square of two.

vec <- 1:3                      
vec                            
[1] 1 2 3

Now, based on the ^ symbol we can calculate the square, Let’s see

vec^2                          
[1] 1 4 9

Now we can try based on the * symbol

Kruskal Wallis test in R-One-way ANOVA Alternative »

Instead of the ^ symbol, insert the * symbol

vec * vec                   
[1] 1 4 9

In another case, simply put

vec**2
[1] 1 4 9

Example 3:-

Square of a data frame, Let’s create a numerical data frame for square calculation

data <- data.frame(x1 = 1:3,  
                      x2 = 2:4,
                      x3 = 2)
data                           
  x1 x2 x3
1  1  2  2
2  2  3  2
3  3  4  2

We can apply the same code ^ symbol for square calculation.

Repeated Measures of ANOVA in R Complete Tutorial »

data^2 
x1 x2 x3
1  1  4  4
2  4  9  4
3  9 16  4

Let’s calculate  based on * symbol

data**2
  x1 x2 x3
1  1  4  4
2  4  9  4
3  9 16  4

or

data*data
  x1 x2 x3
1  1  4  4
2  4  9  4
3  9 16  4

Let’s try sapply function for square calculation.

 sapply(data, function(x) x^2)
     x1 x2 x3
[1,]  1  4  4
[2,]  4  9  4
[3,]  9 16  4

Look’s fine, Let me know if you are using any other function for the square calculation.

Subscribe the Newsletter and COMMENT below!

[newsletter_form type=”minimal”]

rbind in r-Combine Vectors, Matrix or Data Frames by Rows »

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

9 + four =