Dataset reshape and create new columns
2 次查看(过去 30 天)
显示 更早的评论
Hello all,
I am have problems with dataset reshaping and wrangling. I have a file with dataset in the form as shown in the example data attached, every 4 columns are in one group, the first row is the sample ID, and the second row contains the information of the variables. I am wondering whether there are any ways to concatenate all the groups vertically, and create new column names with the information from the sample ID (specifically, text before underscore as "SampleType", and that after the underscore as "replicateID"). In the end the output dataset should have the original 4 columns and the newly added two columns.
Thank you very much for the help!
0 个评论
采纳的回答
Voss
2022-3-30
Here's one way to do it:
% read the file:
data = readcell('example_data.csv');
data(1:10,:)
% get the types and ids:
C = regexp(data(1,:),'(.+)_(.+)','tokens');
C = [C{:}];
type_id = vertcat(C{:})
% do the reshaping and column-prepending operations:
[nrows,ncols] = size(data);
new_data = ['SampleType' 'replicateID' data(2,1:4); ... % first row: variable names
repelem(type_id,(nrows-2)/4,1) ... % first two columns: types and IDs
reshape(permute(reshape(data(3:end,:),[],4,ncols/4),[1 3 2]),[],4)]; % columns 3-6: numeric data cells
% fill "missing" cells with a scalar NaN value:
new_data(cellfun(@(x)isa(x,'missing'),new_data)) = {NaN};
new_data(1:10,:) % check the top
new_data(nrows+(-5:4),:) % check the transition from nonyeasted to yeasted
% write the new file:
writecell(new_data,'example_data_modified.csv');
Read the documentation for reshape, permute, and repelem to understand how they are used here.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!