2014-04-12 42 views
0

我將爲我的問題作序,我是R的新手,並且從未編程過任何其他語言。我一直在閱讀本網站上關於循環和應用功能的主題。這個問題可能被認爲是重複的,但我沒有找到解決方案來滿足我的需求。我有一個簡單的腳本,我想應用於文件夾中的所有文件。我想要發生的事情是,腳本將應用於文件夾中的每個文件,並提供包含每個文件結果的輸出文件。我原本以爲這將是一個批處理程序,但從我所有的搜索看來,它看起來像一個循環更合適。如何將循環應用於我的R腳本

我試圖從applying R script prepared for single file to multiple files in the directory實施方法。

這是我目前:

library("moments") 
    library("lattice") 
    listfile<- dir() ## Creates a list of the files in the folder 
    listfile<- c("raster01_table.csv","Test.csv", "Test2.csv") 
    lst<-vector("list", length(listfile)) #don't know what this is doing 
    names(lst) <-listfile # or this 
    lst[listfile[i]] ## or this 

    #The generalized process to calculate the 4 moments 
    for (i in 1:length(listfile)) { 
    tmp.df <- read.csv(listfile[i], header = T) 
    names(tmp.df)[1]<- c("Value") #DEFINES COLUMN NAMES 
    names(tmp.df)[2]<- c("Count") #DEFINES COLUMN NAMES 
    ##CALCULATES THE FOUR MOMENTS + 1 (IS THE SECOND MOMENT SD OR VAR?) 
    objMean <-mean(tmp.df$Value) #calculates the mean of Value column 
    objSD <-sd(tmp.df$Value) #calculates the standard deviation of Value column 
    objVar <-var(tmp.df$Value) #Calculates the variance of Value column 
    objSkewness <-skewness(tmp.df$Value, na.rm = FALSE) #calculate the skewness of Value Column 
    objKurtosis <-kurtosis(tmp.df$Value, na.rm = FALSE) #Calculate the kurtosis of Value column 
    } 

這段代碼的問題是,它似乎只在列表中的第一個文件運行,因此不會處理該文件夾中的剩餘文件。

回答

1

我一直在處理這類問題。你必須在dir()命令中做一些小的改動。這是新的腳本

library("moments") 
library("lattice") 

listfile <- dir(getwd(),  #This call the working directory 
      pattern = "csv", #This define the kind of files that you need to process 
      recursive = TRUE, #This use the files in the subdirectories 
      all.files = TRUE, #This indicate that you will process all the files 
      full.names = TRUE) #This load the full path of a file 

#The generalized process to calculate the 4 moments 
for (i in 1:length(listfile)) { 
    tmp.df <- read.csv(listfile[i], header = T) 
    names(tmp.df)[1]<- c("Value") #DEFINES COLUMN NAMES 
    names(tmp.df)[2]<- c("Count") #DEFINES COLUMN NAMES 
    ##CALCULATES THE FOUR MOMENTS + 1 (IS THE SECOND MOMENT SD OR VAR?) 
    objMean <-mean(tmp.df$Value) #calculates the mean of Value column 
    objSD <-sd(tmp.df$Value) #calculates the standard deviation of Value column 
    objVar <-var(tmp.df$Value) #Calculates the variance of Value column 
    objSkewness <-skewness(tmp.df$Value, na.rm = FALSE) #calculate the skewness of Value   Column 
    objKurtosis <-kurtosis(tmp.df$Value, na.rm = FALSE) #Calculate the kurtosis of Value  column 
} 
+0

謝謝你,我也非常感謝你如何定義每一行爲我這樣的新手做了什麼。 – user3525495