How to square all the values in a vector in R?
Asked Answered
G

4

32

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)}
Garbanzo answered 24/1, 2014 at 0:16 Comment(0)
V
62

Try this (faster and simpler):

newData <- data^2
Vasoconstrictor answered 24/1, 2014 at 0:19 Comment(1)
@Garbanzo I recommend you take a look to the Quick R tutorial.Vasoconstrictor
D
18

This will also work

newData <- data*data
Drunkometer answered 24/1, 2014 at 0:24 Comment(1)
It's also twice as fast as data^2!Filigreed
C
9

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

newData<- sapply(data, function(x) x^2)
Catachresis answered 24/1, 2014 at 0:56 Comment(2)
I don't know how this is even different/better from the answer provided by @VasoconstrictorHerndon
its will be even slower than the vectorized implementation. sapply is an compact way of writing a loop!Subdivide
Y
0

This is another simple way:

sq_data <- data**2

Yogini answered 1/8, 2020 at 1:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.