user3919708
user3919708

Reputation: 141

loop problems in R

I have a dataframe with this column x$multX1992

x$multX1992;

0 30 30 30 12  5  6  0  0  0  0  0

me92;
0.6531792

created an empty vector to store things in

tmp<- rep(NA, length(x$multX1992));
tmp;
NA NA NA NA NA NA NA NA NA NA NA NA

created this loop to subtract me92 from each value in x$multX1992 and store them in the empty vector.

for(i in seq(x$multX1992)){ tmp[i]<- (i - me92)^2}

What am I doing wrong? The math doesn't add up.

Upvotes: 1

Views: 41

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

You don't need a for loop for this task, just take advantage of R's vectorized way to do things

> x <- data.frame(multX1992=c(0,30,30,30, 12,5,6,0,0,0,0,0))
> me92 <- 0.6531792
> tmp <- (x$multX1992-me92)^2
> tmp
        multX1992
 [1,]   0.4266431
 [2,] 861.2358911
 [3,] 861.2358911
 [4,] 861.2358911
 [5,] 128.7503423
 [6,]  18.8948511
 [7,]  28.5884927
 [8,]   0.4266431
 [9,]   0.4266431
[10,]   0.4266431
[11,]   0.4266431
[12,]   0.4266431

Upvotes: 2

Related Questions