如何将循环应用于我的R脚本
我将在我的问题之前说明,我是R新手,从未用任何其他语言编写过程序。我一直在阅读这个网站上关于循环和应用函数的主题。这个问题可能被认为是重复的,但我并没有找到解决我需要的办法。我有一个简单的脚本,我想应用到一个文件夹中的所有文件。我希望脚本应用于文件夹中的每个文件,并提供一个输出文件,其中包含每个文件的结果。我原本以为这是一个批处理过程,但从我所有的搜索来看,循环似乎更合适 我已尝试从中实施该方法 这就是我目前拥有的:如何将循环应用于我的R脚本,r,loops,R,Loops,我将在我的问题之前说明,我是R新手,从未用任何其他语言编写过程序。我一直在阅读这个网站上关于循环和应用函数的主题。这个问题可能被认为是重复的,但我并没有找到解决我需要的办法。我有一个简单的脚本,我想应用到一个文件夹中的所有文件。我希望脚本应用于文件夹中的每个文件,并提供一个输出文件,其中包含每个文件的结果。我原本以为这是一个批处理过程,但从我所有的搜索来看,循环似乎更合适 我已尝试从中实施该方法 这就是我目前拥有的: library("moments") library("lat
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
}
库(“时刻”)
图书馆(“格子”)
listfile我一直在工作中处理这类问题。您必须对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
}
库(“时刻”)
图书馆(“格子”)
listfile谢谢你,我也非常感谢你为我这样的新手定义了每一行内容。