使用“read.csv”在“for循环” [英] using "read.csv" in a "for loop"
问题描述
我有300 * .csv文件与下面相同的格式。文件名称是相同的不同的索引从1到300开始(例如myarray.1.csv myarray.2.csv .... myarray.300。 csv):
-124.5 -123.5 -122.5 -121.5 -120.5 -119.5 -118.5
31.5 0 0 0 0 0 0 0
32.5 0 0 0 0 0 0 0
33.5 0 0 0 0 0 0 0
34.5 0 0 0 0 0 1.1 5980.4
35.5 0 0 0 0 0 0 41
36.5 0 0 0 0.1 0 0 56
37.5 0 0 0 0 0 2.4 0
38.5 0 0 1 0 0.3 0.3 0
39.5 0 0 0 0 4.1 0.1 0
标题是经度,第一列是纬度,其他数组是相应的值。
我想使用for-loop和write.csv逐个读取它们,并将它们转换为矩阵,以丢弃头和第一列,所以我刚刚结束时的值。
我使用这个命令,但似乎它不工作:
setwd(C:/ Users / WF )
for(i in 1:300){
file_new_name < - myarray
file_new_name < - paste(file_new_name,i,sep =。)
file_new_name< ; - 粘贴(file_new_name,。csv,sep =)
file_read< - read.csv(file_new_name,header = TRUE)
}
解决方案这样的模式在我看来效果最好, >
list_of_files = list.files(c:/ User / WF,pattern ='* csv')
list_of_csv = lapply (list_of_files,read.csv)
big_object = do.call('rbind',list_of_csv)
我假设所有要读取的CSV文件都存在于
c:/ User / WF
中。
您必须自行填写详细资料,但这应该让您开始。
I have 300 *.csv file with the same format as below.File names are the same with different index starting from 1 to 300(e.g. myarray.1.csv myarray.2.csv ....myarray.300.csv):
-124.5 -123.5 -122.5 -121.5 -120.5 -119.5 -118.5 31.5 0 0 0 0 0 0 0 32.5 0 0 0 0 0 0 0 33.5 0 0 0 0 0 0 0 34.5 0 0 0 0 0 1.1 5980.4 35.5 0 0 0 0 0 0 41 36.5 0 0 0 0.1 0 0 56 37.5 0 0 0 0 0 2.4 0 38.5 0 0 1 0 0.3 0.3 0 39.5 0 0 0 0 4.1 0.1 0
header is longitude and first column is latitude and other arrays are correspondent values.
I want to use "for-loop" and "write.csv" to read them one by one and convert them to a matrix in a way that it discards the header and first column so I have just the values at the end. I used this command but it seems it doesn't work:
setwd("C:/Users/WF") for ( i in 1:300) { file_new_name <- myarray file_new_name <- paste(file_new_name,i,sep=".") file_new_name <- paste(file_new_name,".csv",sep="") file_read <- read.csv(file_new_name,header=TRUE) }
解决方案A pattern like this works best in my opinion, and is very R-like in style:
list_of_files = list.files("c:/User/WF", pattern = '*csv') list_of_csv = lapply(list_of_files, read.csv) big_object = do.call('rbind', list_of_csv)
I assume here that all the CSV files you want to read are present in the
c:/User/WF
.You'll have to fill the details yourself, but this should get you started.
这篇关于使用“read.csv”在“for循环”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!