[r] How to square all the values in a vector in R?

I would like to square every value in data, and I am thinking about using a for loop like this:

data = rnorm(100, mean=0, sd=1)
Newdata = {L = NULL;  for (i in data)  {i = i*i}  L = i  return (L)}

This question is related to r perfect-square

The answer is


Try this (faster and simpler):

newData <- data^2

This is another simple way:

sq_data <- data**2


This will also work

newData <- data*data

How about sapply (not really necessary for this simple case):

newData<- sapply(data, function(x) x^2)