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

4 Answers 4

62

Try this (faster and simpler):

newData <- data^2
1
18

This will also work

newData <- data*data
1
  • 8
    It's also twice as fast as data^2! Commented Jan 24, 2014 at 2:39
9

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

newData<- sapply(data, function(x) x^2)
2
  • I don't know how this is even different/better from the answer provided by @Barranka
    – Ronak Shah
    Commented Dec 28, 2016 at 9:26
  • 1
    its will be even slower than the vectorized implementation. sapply is an compact way of writing a loop!
    – David
    Commented Jan 24, 2017 at 6:35
0

This is another simple way:

sq_data <- data**2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.