Calculate Square in R

[This article was first published on Methods – finnstats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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!

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

The post Calculate Square in R appeared first on finnstats.

To leave a comment for the author, please follow the link and comment on their blog: Methods – finnstats.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)