How can I add new column in a dataset array but not at the end?

2 次查看(过去 30 天)
I have a dataset array [202x89] and another one [150x97]. I want to Concatenate arrays but they must have the same number of variables and All datasets in the bracketed expression must have the same variable names. The new columns that i want to insert in the first dataset i want to be 'NaN'. That's ok but but i want to specify the position of a new column (to use after all the vertcat function). Can you help me please.
Thanks

采纳的回答

Peter Perkins
Peter Perkins 2012-1-17
Alexis, I am niot 100% sure from your description exactly what you are trying to do. I'm going to assume that you want to create a new dataset that is a vertical concatenation of the first dataset and the second. But since the first has fewer variables, you need to create the missing variables, and you'd like to fill them with NaN.
You mention wanting to insert variables in the first dataset. You can only create a new variables at the end. So if you want to insert new variables in the middle, you need to take two steps: create them at the end, and then use subscripting to rearrange. Given this ...
a = dataset(randn(10,1),randn(10,1),'VarNames',{'W' 'X'});
... you can do something like this ...
a(:,{'Y' 'Z'}) = dataset(NaN(10,1),NaN(10,2));
a = a(:,[1 3:4 2])
... to rearrange. But there may not be any need to do this. Concatenation for dataset works by matching up variable names, and it doesn't matter what order they are in. So you can concatenate these two arrays
a = dataset(randn(10,1),randn(10,1),'VarNames',{'X' 'Y'});
b = dataset(randn(10,1),randn(10,1),'VarNames',{'Y' 'X'});
even though the variables are in a different order.

更多回答(1 个)

David Young
David Young 2012-1-17
To insert a column of NaNs after column c of matrix A, you could use
Anew = [A(:,1:c) NaN(size(A,1),1) A(:, c+1:end)];
To insert k columns of NaNs after column c, use
Anew = [A(:,1:c) NaN(size(A,1),k) A(:, c+1:end)];
  2 个评论
alexis
alexis 2012-1-17
thanks for your reply but i have this msg:
Error using ==> dataset.horzcat at 33
All input arguments must be datasets.
Can you help me?
David Young
David Young 2012-1-18
You didn't say that dataset is a class of the Statistics Toolbox. I can't help with that.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by