user3230065
user3230065

Reputation: 331

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)}

Upvotes: 33

Views: 165179

Answers (4)

RICARDO LINO
RICARDO LINO

Reputation: 1

This is another simple way:

sq_data <- data**2

Upvotes: 0

desired login
desired login

Reputation: 1190

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

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

Upvotes: 9

Jota
Jota

Reputation: 17621

This will also work

newData <- data*data

Upvotes: 18

Barranka
Barranka

Reputation: 21067

Try this (faster and simpler):

newData <- data^2

Upvotes: 63

Related Questions