首页 > 解决方案 > 基于特定变量重新采样数据

问题描述

我有一个大型数据集,如下所示。从数据中,我想根据“id”随机抽样。由于数据有 5 个 id,我想对 5 个 id 进行替换采样,并生成一个新的数据集,其中包含对采样 id 的观察。

 id value   var1    var2    …
  1 1           
  1 2           
  1 3           
  1 4           
  2 5           
  2 6           
  2 7           
  3 8           
  3 9           
  3 10          
  4 11          
  4 12          
  4 13          
  5 14          
  5 15          
  5 16          

假设,我从 1 到 5 随机抽取 5 个值(因为有 5 个唯一 id),结果是 (2 4 3 2 1)。然后,我想拥有这些数据

  id    value   var1    var2    …
  2 5           
  2 6           
  2 7           
  4 11          
  4 12          
  4 13          
  3 8           
  3 9           
  3 10          
  2 5           
  2 6           
  2 7           
  1 1           
  1 2           
  1 3           
  1 4   

标签: matlabresampling

解决方案


下面是从 1 到 5 的 id 的示例代码。

% data = [1 1; 1 2; 1   3; 1 4; 2 5; 2 6; 2 7; 3 8; 3 9; 3 10; 4 11; 4 12; 4 13;...
%     5 14; 5   15; 5 16];
data = rand(10000000,10);
data(:,1) = randi([1,5], length(data),1);

% Get all the indices from the 1st column;
indxCell = cell(5,1);
for i=1:5
    tmpIndx = find(data(:,1) == i);
    indxCell{i} = tmpIndx;
end

% Rearrange the indices
randIndx = randperm(5);
randIndxCell = indxCell(randIndx, 1);

% Generate a vector of indices by rearranging the 1st column of data matrix. 
numDataPts = length(data);
newIndices = zeros(numDataPts,1);
endIndx = 1;
for i=1:5
    startIndx = endIndx;
    endIndx = startIndx + length(randIndxCell{i});
    newIndices(startIndx:endIndx-1, 1) = randIndxCell{i};
end

newData = data(newIndices,:);

对于更多唯一 ID,您可以修改代码。

编辑:修改了数据大小并重写了第二个 for 循环。


推荐阅读