2016-05-12 22 views
0

我正在嘗試重新組織一些數據。這裏是文件的描述:控制檯在R中的循環之後無響應

60 csv files 
40 columns 
250 rows 

我想要做的是刪除無用的列,使其更具可讀性。我選擇用循環做到這一點。我的代碼:

file.number <- paste0(rep(c(1:30), each = 2), rep(c('a','b')), '.csv') # lists file names (works fine) 

d1 <-setNames(lapply(file.number, read.csv, stringsAsFactors=FALSE),paste(file.number)) # imports data into r (works fine) 
i = 1 
while (i <= length(file.number)){ 
    index <- i # indexs 
    nam <- paste0("d2",i) # creates new file name (same problem with this line of code removed) 
    d2 <- subset(d1[[index]], select = c('column.1','column.2','column.2')) # If i run this line of code outside the loop by just indexing a specific file it runs fine, it just doesn't work in the loop 
    assign(nam, d2) # creates a new file name (I run into the same problem with this line of code removed 
} 

因此,當我運行此循環時,R控制檯變得無響應。我已經運行循環非常類似於此,沒有問題。有誰知道這個問題可能是什麼?

回答

1

嘗試將您的環路控制while (i <= length(file.number))更換爲for (i in 1:length(file.number))。隨着循環的進行,這將增加i。否則在while循環內放入i <- i + 1

一個簡單的調試技巧:下次你可以在你的循環中插入一個print(i)並運行它。如果程序確實有效,你會看到i一直在增加;否則你知道有什麼問題。

1

i始終爲1,因此您的while循環會一直持續。