matlab - 基于特定变量重新采样数据
问题描述
我有一个大型数据集,如下所示。从数据中,我想根据“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
解决方案
下面是从 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 循环。
推荐阅读
- babeljs - 如何创建一个供内部使用的 babel 插件
- jmeter - 在使用soap webservice配置时,我有数千个用Jmeter 2.11编写的测试用例。我收到“测试元素已过时”
- linux - 颜色和 printf 的 Bash 函数问题
- java - '证书必须有一个 ExtendedKeyUsage 扩展。和“加载扩展部分 config.cnf 时出错”
- sql - ORA-01789: 查询块的结果列数不正确
- python - 从少于 4 位的列表中提取数字,并在每个数字的开头和结尾附加一个字符串
- sql - 解析分隔数据并匹配单个值
- maven - AJC maven 编译项目上的 Dagger2
- android - Branch.io - 当应用程序从任务切换器返回前台时调用 AttributionListener onResult
- javascript - 查询至少有 1 个关联,但返回所有