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!