Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in lis[[i]] : attempt to select less than one element

Tags:

r

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 
like image 524
Tommy Yu Avatar asked May 03 '15 23:05

Tommy Yu


Video Answer


1 Answers

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]])   } 
like image 107
Aadithya_h Avatar answered Sep 30 '22 13:09

Aadithya_h