2015-03-03 139 views
0

我有一个文件夹充满'N'个大小为(m,n)的.csv文件。我想导入它们,同时将每个文件转换为一个大小为(mxn)的列矩阵,并将它们存储在一个(mxn,N)大小的矩阵中,每列都有相应文件的名称。导入许多csv文件

我的代码无法从.csv文件中检索数据并显示错误。这些数据是一个月平均降雨量数据,有13列(年,jan,feb ...... dec),我不想输入年份列,因为它没有降雨值而只是年份值。

我的代码是

list=dir('*.csv'); 
N=numel(list); 
h=zeros(1300,N); 
for k =1:1:N; 
    data=csvread(list(k).name); 
    M=size(data); 
    for j=1:M(1) 
     for i=1:M(1) 
      h(i+1+(j-1)*12,k)=data(j,i); 
     end 
    end 
end 

这里h是我想要存储的所有数据的矩阵。

Error using dlmread (line 138) 
Mismatch between file and format string. 
Trouble reading number from file (row 1u, field 1u) ==> "Year" "Jan" "Feb" 
"Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"\n 

虽然上面的代码是在matlab中,但在R编程语言中的任何回复也是可以接受的。

+0

R中的工作流已经被描述了很多次。请按照“导入多个文件”的方式进行搜索。为了缩小它,你需要函数'list.files()','do.call()',当然还有'read.table()'或者它的任何变体。 – 2015-03-03 08:45:57

+0

'csvread'仅用于数字数据。你必须使用另一个函数来读入,例如这样:http://stackoverflow.com/questions/6759657/reading-text-data-from-a-csv-file-in-matlab – Daniel 2015-03-03 08:48:51

+0

可能的重复[Import具有混合数据类型的CSV文件](http://stackoverflow.com/questions/4747834/import-csv-file-with-mixed-data-types) – Daniel 2015-03-03 08:53:49

回答

0

如果您查看csvread文档,它指出该文件必须只包含数字值。由于您的文件包含其他数据类型(如字符串),因此您可以使用textscan(有关更多详细信息,请参阅文档)。

请看这个thread的计算器。已使用使用textscan和fgetl的自定义函数来读取混合数据类型的csv文件。下面的代码取自上面提到的线程。代码已在gnovice所写的答案中提供。

function lineArray = read_mixed_csv(fileName,delimiter) 
    fid = fopen(fileName,'r'); %# Open the file 
    lineArray = cell(100,1);  %# Preallocate a cell array (ideally slightly 
           %# larger than is needed) 
    lineIndex = 1;    %# Index of cell to place the next line in 
    nextLine = fgetl(fid);  %# Read the first line from the file 
    while ~isequal(nextLine,-1)   %# Loop while not at the end of the file 
    lineArray{lineIndex} = nextLine; %# Add the line to the cell array 
    lineIndex = lineIndex+1;   %# Increment the line index 
    nextLine = fgetl(fid);   %# Read the next line from the file 
    end 
    fclose(fid);     %# Close the file 
    lineArray = lineArray(1:lineIndex-1); %# Remove empty cells, if needed 
    for iLine = 1:lineIndex-1    %# Loop over lines 
    lineData = textscan(lineArray{iLine},'%s',... %# Read strings 
         'Delimiter',delimiter); 
    lineData = lineData{1};    %# Remove cell encapsulation 
    if strcmp(lineArray{iLine}(end),delimiter) %# Account for when the line 
     lineData{end+1} = '';      %# ends with a delimiter 
    end 
    lineArray(iLine,1:numel(lineData)) = lineData; %# Overwrite line data 
    end 
end 

运行的功能很简单,只要

data_csv = read_mixed_csv('filename.csv', ','); 

的功能可以很容易地修改,以满足您的需求。希望它有帮助