Chandler Nelson
Chandler Nelson

Reputation: 35

number of items to replace is not a multiple of replacement length error in R

I have the following loop that I am trying to run but I keep getting the error "number of items to replace is not a multiple of replacement length". Can anyone help me as to why this is happening? Also, I need to somehow include my angles vector into my matrix and don't know how. Here is my loop so far:

anglematrix <- numeric()
for(i in 1:length(fish2$X))
{
    a1 <- as.numeric(fish2[1, c(1,2)])
    a2 <- as.numeric(fish2[1 + 1, c(1,2)])
    a3 <- as.numeric(fish2[1 + 2, c(1,2)])

    angles <- Angle(a1, a2, a3, label=FALSE)
    anglematrix[i] <- matrix(NA, nrow=length(fish2$X)-2, ncol=1)
}

Here is the structure of my data set with the first six lines

structure(list(X = c(147.8333333, 148.5, 151.1666667, 154.5,158.1666667, 161.5), Y = c(258.5, 258.8333333, 260.8333333, 264.5,266.5, 269.5)), row.names = c(NA, 6L), class = "data.frame")

output should be 176 angle calculations in a single column within the matrix. Thanks for the help!

Upvotes: 0

Views: 1011

Answers (1)

dww
dww

Reputation: 31452

There are quite a number of things wrong in your original code, but the following works and should give you guidance about where you were going wrong. Probably the most importnt thing to see is that you should define an empty matrix before the loop, and fill its values within the loop, using the iterator i to specify which value you update each time. NB I assume that you are using Angle from library(LearnGeom), as you did not specify the source of this function:

Nangles = NROW(fish2) - 2
anglematrix = matrix(nr = Nangles, nc=1)

for(i in 1:Nangles) {
  a1 <- as.numeric(fish2[i, ])
  a2 <- as.numeric(fish2[i + 1, ])
  a3 <- as.numeric(fish2[i + 2, ])
  anglematrix[i] <- Angle(a1, a2, a3, label=FALSE)
}

Upvotes: 1

Related Questions