Main Content

添加和删除表行

此示例演示了如何在表中添加和删除行。您也可以使用变量编辑器来编辑表。

加载样本数据

加载样本患者数据并创建一个表 T

load patients
T = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);
size(T)
ans = 1×2

   100     8

T 包含 100 行和 8 个变量。

通过串联添加行

将多位患者的数据从逗号分隔的文件 morePatients.csv 读入到表 T2 中。然后,将 T2 中的行追加到表 T 的末尾。

T2 = readtable('morePatients.csv');
Tnew = [T;T2];
size(Tnew)
ans = 1×2

   104     8

Tnew 包含 104 行。要垂直串联两个表,这两个表必须具有相同的行数和相同的变量名称。如果变量名称不同,您可以将一个表中的行直接指定给另一个表,以此方式来插入新行。例如,T(end+1:end+4,:) = T2

从元胞数组添加行

要追加元胞数组中存储的新行,请将元胞数组垂直串联到表的末尾。当元胞数组具有正确的列数并且其元胞的内容可以串联到对应的表变量上时,您可以直接从元胞数组进行串联。

cellPatients = {'Trujillo','Male',42,70,158,0,116,83;
                'Falk','Female',28,62,125,1,120,71};
Tnew = [Tnew;cellPatients];
size(Tnew)
ans = 1×2

   106     8

您也可以使用 cell2table 函数将元胞数组转换为表。

从结构体添加行

您也可以追加存储于结构体中的行。将该结构体转换为表,然后串联表。

structPatients(1,1).LastName = 'George';
structPatients(1,1).Gender = 'Nonbinary';
structPatients(1,1).Age = 45;
structPatients(1,1).Height = 76;
structPatients(1,1).Weight = 182;
structPatients(1,1).Smoker = 1;
structPatients(1,1).Systolic = 132;
structPatients(1,1).Diastolic = 85;

structPatients(2,1).LastName = 'Russo';
structPatients(2,1).Gender = 'Female';
structPatients(2,1).Age = 29;
structPatients(2,1).Height = 58;
structPatients(2,1).Weight = 120;
structPatients(2,1).Smoker = 0;
structPatients(2,1).Systolic = 112;
structPatients(2,1).Diastolic = 70;

Tnew = [Tnew;struct2table(structPatients)];
size(Tnew)
ans = 1×2

   108     8

忽略重复的行

要忽略表中的任何重复行,请使用 unique 函数。

Tnew = unique(Tnew);
size(Tnew)
ans = 1×2

   107     8

unique 删除了两个重复行。

按行号删除行

删除表中的第 18、20 和 21 行。

Tnew([18,20,21],:) = [];
size(Tnew)
ans = 1×2

   104     8

此表现在包含 103 位患者的信息。

按行名称删除行

首先,将标识符变量 LastName 指定为行名称。然后,从 Tnew 中删除变量 LastName。最后,使用行名称为这些行建立索引并将这些行删除。

Tnew.Properties.RowNames = Tnew.LastName;
Tnew.LastName = [];
Tnew('Smith',:) = [];
size(Tnew)
ans = 1×2

   103     7

现在,表比之前少了一行和一个变量。

搜索要删除的行

您也可以搜索表中的观测值。例如,删除年龄在 30 岁以下的所有患者对应的行。

toDelete = Tnew.Age < 30;
Tnew(toDelete,:) = [];
size(Tnew)
ans = 1×2

    86     7

现在,表比之前少了 17 行。

另请参阅

| | | |

相关主题