32

This code is meant to compute the total distance of some given coordinates, but I don't know why it's not working.

The error is: Error in lis[[i]] : attempt to select less than one element.

Here is the code:

distant<-function(a,b)
{
  return(sqrt((a[1]-b[1])^2+(a[2]-b[2])^2))
}
totdistance<-function(lis)
{
  totdis=0
  for(i in 1:length(lis)-1)
  {
    totdis=totdis+distant(lis[[i]],lis[[i+1]])
  }
  totdis=totdis+distant(lis[[1]],lis[[length(lis)]])
  return(totdis)
}
liss1<-list()
liss1[[1]]<-c(12,12)
liss1[[2]]<-c(18,23)
liss1[[4]]<-c(29,25)
liss1[[5]]<-c(31,52)
liss1[[3]]<-c(24,21)
liss1[[6]]<-c(36,43)
liss1[[7]]<-c(37,14)
liss1[[8]]<-c(42,8)
liss1[[9]]<-c(51,47)
liss1[[10]]<-c(62,53)
liss1[[11]]<-c(63,19)
liss1[[12]]<-c(69,39)
liss1[[13]]<-c(81,7)
liss1[[14]]<-c(82,18)
liss1[[15]]<-c(83,40)
liss1[[16]]<-c(88,30)

Output:

> totdistance(liss1)
Error in lis[[i]] : attempt to select less than one element
> distant(liss1[[2]],liss1[[3]])
[1] 6.324555
sbolel
  • 3,486
  • 28
  • 45
Tommy Yu
  • 1,080
  • 3
  • 11
  • 30
  • 5
    You should replace `for(i in 1:length(lis)-1)` with `for(i in 1:(length(lis)-1))`. The `:` operator is evaluated before the subtraction `-`. – Molx May 03 '15 at 23:23
  • 1
    And while we're at it, a matrix is probably a better fit for a polygon data than a list, unless there are other properties to be saved. – Molx May 03 '15 at 23:27

1 Answers1

37

Let me reproduce your error in a simple way

>list1 = list()  
> list1[[0]]=list(a=c("a"))  
>Error in list1[[0]] = list(a = c("a")) : 
attempt to select less than one element

So, the next question is where are you accessing 0 index list ? (Indexing of lists starts with 1 in R )

As Molx, indicated in previous posts : "The : operator is evaluated before the subtraction - " . This is causing 0 indexed list access.

For ex:

> 1:10-1  
[1] 0 1 2 3 4 5 6 7 8 9  
>1:(10-1)  
[1] 1 2 3 4 5 6 7 8 9

So replace the following lines of your code

>for(i in 1:(length(lis)-1))  
{     
     totdis=totdis+distant(lis[[i]],lis[[i+1]])  
}
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Aadithya_h
  • 561
  • 6
  • 6