要更改 xtab 表中的列变量和行变量的名称,我们可以使用 setNames 函数。
例如,如果我们有一个名为 XTAB 的 xtab 表,并且我们想要更改列变量名称 C 和行变量名称 R,那么我们可以使用以下命令 -
dimnames(XTAB)<-setNames(dimnames(XTAB),c("R","C"))
以下代码段创建了一个示例数据框 -
Table1<-xtabs(~as.factor(letters[1:5])+letters[1:5]) Table1
创建了以下数据框
letters[1:5] as.factor(letters[1:5]) a b c d e a 1 0 0 0 0 b 0 1 0 0 0 c 0 0 1 0 0 d 0 0 0 1 0 e 0 0 0 0 1
要在上面创建的数据框中更改 Table1 中的列和行变量名称,请将以下代码添加到上面的代码段中 -
Table1<-xtabs(~as.factor(letters[1:5])+letters[1:5]) dimnames(Table1)<-setNames(dimnames(Table1),c("Rows","Columns")) Table1输出结果
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
Columns Rows a b c d e a 1 0 0 0 0 b 0 1 0 0 0 c 0 0 1 0 0 d 0 0 0 1 0 e 0 0 0 0 1
以下代码段创建了一个示例数据框 -
Cat1<-sample(c("Hot","Cold"),20,replace=TRUE) Cat2<-sample(c("Low","Medium","High"),20,replace=TRUE) dat1<-data.frame(Cat1,Cat2) dat1
创建了以下数据框
Cat1 Cat2 1 Cold High 2 Hot High 3 Hot High 4 Hot High 5 Cold Low 6 Hot Low 7 Hot Medium 8 Hot Low 9 Cold Medium 10 Hot High 11 Hot Low 12 Cold Low 13 Hot Low 14 Hot Low 15 Hot Medium 16 Cold Medium 17 Hot Medium 18 Hot Low 19 Hot High 20 Cold Medium
将以下代码添加到上述代码段中 -
Cat1<-sample(c("Hot","Cold"),20,replace=TRUE) Cat2<-sample(c("Low","Medium","High"),20,replace=TRUE) dat1<-data.frame(Cat1,Cat2) Table2<-xtabs(~Cat1+Cat2,data=dat1) Table2输出结果
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
Cat2 Cat1 High Low Medium Cold 1 2 3 Hot 5 6 3
要在上面创建的数据框中更改 Table2 中的列和行变量名称,请将以下代码添加到上面的代码段中 -
Cat1<-sample(c("Hot","Cold"),20,replace=TRUE) Cat2<-sample(c("Low","Medium","High"),20,replace=TRUE) dat1<-data.frame(Cat1,Cat2) Table2<-xtabs(~Cat1+Cat2,data=dat1) dimnames(Table2)<-setNames(dimnames(Table2),c("Group1","Group2")) Table2输出结果
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
Group2 Group1 High Low Medium Cold 1 2 3 Hot 5 6 3
以下代码段创建了一个示例数据框 -
Level_1<-sample(c("Upper","Lower"),20,replace=TRUE) Level_2<-sample(c("Super","top-notch"),20,replace=TRUE) dat2<-data.frame(Level_1,Level_2) dat2
创建了以下数据框
Level_1 Level_2 1 Upper top-notch 2 Lower Super 3 Lower top-notch 4 Lower Super 5 Upper top-notch 6 Upper top-notch 7 Lower top-notch 8 Lower top-notch 9 Upper top-notch 10 Lower top-notch 11 Upper Super 12 Upper top-notch 13 Lower top-notch 14 Lower top-notch 15 Upper top-notch 16 Lower top-notch 17 Upper top-notch 18 Lower top-notch 19 Lower Super 20 Upper Super
将以下代码添加到上述代码段中 -
Level_1<-sample(c("Upper","Lower"),20,replace=TRUE) Level_2<-sample(c("Super","top-notch"),20,replace=TRUE) dat2<-data.frame(Level_1,Level_2) Table3<-xtabs(~Level_1+Level_2,data=dat2) Table3输出结果
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
Level_2 Level_1 Super top-notch Lower 3 8 Upper 2 7
要在上面创建的数据框中更改 Table3 中的列和行变量名称,请将以下代码添加到上面的代码段中 -
Level_1<-sample(c("Upper","Lower"),20,replace=TRUE) Level_2<-sample(c("Super","top-notch"),20,replace=TRUE) dat2<-data.frame(Level_1,Level_2) Table3<-xtabs(~Level_1+Level_2,data=dat2) dimnames(Table3)<-setNames(dimnames(Table3),c("Minor","Major")) Table3输出结果
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
Major Minor Super top-notch Lower 3 8 Upper 2 7