Dataset reshape and create new columns
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Shengyue Shan
el 30 de Mzo. de 2022
Comentada: Voss
el 31 de Mzo. de 2022
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 comentarios
Respuesta aceptada
Voss
el 30 de Mzo. de 2022
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.
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Spreadsheets en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!