添加和删除表行
这个例子展示了如何在表中添加和删除行。您还可以使用变量编辑器编辑表。
加载样例数据
加载样本患者数据并创建一个表,T
.
负载病人T = table(姓氏,性别,年龄,身高,体重,吸烟,收缩压,舒张压);大小(T)
ans =1×2100年8
桌上,T
,有100行和8个变量(列)。
按串联方式添加行
从逗号分隔的文件中读取更多患者的数据,morePatients.csv
,变成一个表,T2
.然后,追加来自的行T2
到桌子的尽头,T。
T2 =可读(“morePatients.csv”);Tnew = [T;T2];大小(Tnew)
ans =1×2104年8
表Tnew
有104行。为了垂直连接两个表,两个表必须具有相同数量的变量和相同的变量名。如果变量名不同,则可以直接将表中的新行分配给来自另一个表的行。例如,T(end+1:end+4,:) = T2
.
从单元格数组中添加行
若要追加存储在单元格数组中的新行,请将单元格数组垂直连接到表的末尾。当单元格数组具有正确的列数并且单元格的内容可以连接到相应的表变量时,可以直接从单元格数组进行连接。
cellPatients = {“爱德华”,“男”、42、70158、0116、83;“福尔克”,“女”, 28岁,62125、1120、71};Tnew = [Tnew;cell患者];大小(Tnew)
ans =1×2106年8
方法将单元格数组转换为表cell2table
函数。
从结构中添加行
还可以追加存储在结构中的新行。将结构转换为表,然后连接表。
structPatients(1, 1)。LastName =“乔治”;structPatients(1, 1)。性别=“男”;structPatients(1, 1)。年龄= 45岁;structPatients(1, 1)。身高= 76;structPatients(1, 1)。体重= 182;structPatients(1, 1)。吸烟者= 1;structPatients(1, 1)。收缩压= 132;structPatients(1, 1)。舒张= 85;structPatients(2, 1)。LastName =“哈德利”;structPatients(2, 1)。性别=“女”;structPatients(2, 1)。年龄= 29;structPatients(2, 1)。身高= 58;structPatients(2, 1)。重量= 120;structPatients(2, 1)。吸烟者= 0;structPatients(2, 1)。收缩压= 112;structPatients(2, 1)。舒张= 70;Tnew = [Tnew;struct2table(structPatients)];大小(Tnew)
ans =1×2108年8
省略重复行
若要省略表中复制的任何行,请使用独特的
函数。
Tnew =唯一的(Tnew);大小(Tnew)
ans =1×2106年8
独特的
删除了两个重复的行。
按行号删除行
从表中删除第18、20和21行。
Tnew([18,20,21],:) = [];大小(Tnew)
ans =1×2103年8
该表包含103名患者的信息。
按行名删除行
首先,指定变量标识符,姓
,作为行名。然后,删除变量,姓
,从Tnew
.最后,使用行名来索引和删除行。
Tnew.Properties.RowNames = Tnew.LastName;Tnew。LastName = [];Tnew (“史密斯”,:) = [];大小(Tnew)
ans =1×2102年7
现在表格少了一行,少了一个变量。
搜索要删除的行
您还可以在表中搜索观察结果。例如,删除年龄在30岁以下的所有患者的行。
toDelete = Tnew。年龄< 30岁;Tnew(toDelete,:) = [];大小(Tnew)
ans =1×285年7
现在表少了17行。
另请参阅
表格
|readtable
|array2table
|cell2table
|struct2table