R:遍历目录

问题描述:

我想实现R中下面的算法:给定一个列表R:遍历目录

Iterate(Cell: top) 
    While (top != null) 
     Print top.Value 
     top = top.Next 
    End While 
End Iterate 

基本上,算法应尽快打破,因为它击中“空”甚至当列表不过度。

myls<-list('africa','america south','asia','antarctica','australasia',NULL,'europe','america north') 

我不得不添加一个for循环使用is.null()函数,但下面的代码是灾难,我需要你的帮助来解决它。

Cell <- function(top) { 
    #This algorithm examines every cell in the linked list, so if the list contains N cells, 
    #it has run time O(N). 
    for (i in 1:length(top)){ 
    while(is.null(top[[i]]) !=TRUE){ 
     print(top) 
     top = next(top) 
    } 
    } 
} 

您可以使用运行此函数:

Cell(myls) 

你是接近,但也没有必要在此 建设使用for(...)

Cell <- function(top){ 
    i = 1 
    while(i <= length(top) && !is.null(top[[i]])){ 
     print(top[[i]]) 
     i = i + 1 
    } 
} 

正如你看到我添加了一个额外的条件到while循环:i <= length(top)这是为了确保你不会超越 列表的长度的情况下有没有空项。

但是你可以使用一个for循环使用这种结构:

Cell <- function(top){ 
    for(i in 1:length(top)){ 
     if(is.null(top[[i]])) break 
     print(top[[i]]) 
    } 
} 

或者您可以使用此代码没有for/while建设:

myls[1:(which(sapply(myls, is.null))[1]-1)] 
+0

第二次解决方案中的精彩放置位置。伟大的工作Johan,谢谢你分享这三个。 – Bhushan

检查了这一点:它运行一个由一个用于myls中的所有值并打印它们,但是如果它遇到NULL值,它会中断。

for (val in myls) { 
    if (is.null(val)){ 
    break 
    } 
    print(val) 
} 

如果有任何疑问,请告知我。

+0

谢谢G.arima。 – Bhushan

+0

不客气。 –