Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)} 
like image 526
user3230065 Avatar asked Jan 24 '14 00:01

user3230065


People also ask

How do I square an entire column in R?

To add columns with square of each column in R data frame, we can use setNames function and cbind function for squaring each value. This might be required when we want to use squared form of variables in the data analysis.

What is the square function in R?

If r is a number, square(r) is a shortcut for creating a window object representing the square [ 0 , r ] × [ 0 , r ] . It is equivalent to the command owin(c(0,r),c(0,r)) . If r is a vector of length 2, then square(r) creates the square with x and y coordinates ranging from r[1] to r[2] .

How do you use sqrt in R?

Calculate Square root of a number in R Language – sqrt() Function. sqrt() function in R Language is used to calculate the mathematical square-root of the value passed to it as argument. Here, in the above code, NaN is produced because we passed a negative value in the sqrt() function.

What does vector () do in R?

R Programming is. The is. vector() function allows you to check if the object provided as an argument to it is a vector or not. This function takes an argument as an input and returns TRUE if the provided object is a vector. If the provided object is not a vector, this function returns FALSE.


1 Answers

Try this (faster and simpler):

newData <- data^2 
like image 79
Barranka Avatar answered Sep 29 '22 12:09

Barranka