for loop - Why is R adding an extra element to my vector? -
i have create loop takes vector z1, squares it, , creates vector z2 vectors (yes know there vectorization homework problem). i've got down except reason adds on trailing element said vector.
z1 <- c(1, 8, 19, 17, 65, 103, 48, 17, 23, 34) # sort z1 in descending order z1 <- sort(z1, decreasing = true) # create empty vector z2 z2 <- c() (i in 1:10){ z2[i] <- z1[i]*z1[i] z2 <- c(z2,z2[i]) } print(z2)
here's vector prints
[1] 10609 4225 2304 1156 529 361 289 289 64 1 1
if notice has 11 elements while original z1 vector has 10. why?
first point: can operation without loop using vectorized ^
primitive function.
z1 ^ 2 # [1] 10609 4225 2304 1156 529 361 289 289 64 1
but here's what's happening in code. need remove line
z2 <- c(z2, z2[i])
because on previous line have completed assignment of z2
vector, leaving final run c(z2[1:10], z2[10])
. if want continue using loop, remove line.
## note difference in initializing z2 ## memory allocation more efficient building in loop z2 <- vector(typeof(z1), length(z1)) (i in seq_along(z2)) { z2[i] <- z1[i]*z1[i] }
and have
z2 # [1] 10609 4225 2304 1156 529 361 289 289 64 1
Comments
Post a Comment