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)}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user3230065
  • 321
  • 1
  • 3
  • 3

4 Answers4

62

Try this (faster and simpler):

newData <- data^2
Barranka
  • 20,547
  • 13
  • 65
  • 83
18

This will also work

newData <- data*data
Jota
  • 17,281
  • 7
  • 63
  • 93
9

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

newData<- sapply(data, function(x) x^2)
desired login
  • 1,138
  • 8
  • 15
0

This is another simple way:

sq_data <- data**2