如何通过定义列数将向量转换为R中的数据帧?
如果我们有一个向量,其中替代值可以创建表格形式,那么我们可能希望将向量转换为数据帧。为此,我们首先需要将向量转换为具有适当列数/行数的矩阵,然后使用as.data.frame函数将其作为数据帧读取。查看以下示例以了解其工作原理。
例1
> x1<-c(rep(c(1,"male"),times=10),rep(c(2,"female"),times=10)) > x1输出结果
[1] "1" "male" "1" "male" "1" "male" "1" "male" [9] "1" "male" "1" "male" "1" "male" "1" "male" [17] "1" "male" "1" "male" "2" "female" "2" "female" [25] "2" "female" "2" "female" "2" "female" "2" "female" [33] "2" "female" "2" "female" "2" "female" "2" "female"
将x1转换为数据帧-
> x1_df<-as.data.frame(matrix(x1,ncol=2,byrow=TRUE)) > x1_df输出结果
V1 V2 1 1 male 2 1 male 3 1 male 4 1 male 5 1 male 6 1 male 7 1 male 8 1 male 9 1 male 10 1 male 11 2 female 12 2 female 13 2 female 14 2 female 15 2 female 16 2 female 17 2 female 18 2 female 19 2 female 20 2 female
例2
将x2转换为数据帧-
> x2<-c(rep(c("Grp1",rpois(1,1)),times=10),rep(c("Grp2",rpois(1,8)),times=10)) > x2输出结果
[1] "Grp1" "5" "Grp1" "5" "Grp1" "5" "Grp1" "5" "Grp1" "5" [11] "Grp1" "5" "Grp1" "5" "Grp1" "5" "Grp1" "5" "Grp1" "5" [21] "Grp2" "11" "Grp2" "11" "Grp2" "11" "Grp2" "11" "Grp2" "11" [31] "Grp2" "11" "Grp2" "11" "Grp2" "11" "Grp2" "11" "Grp2" "11"
例2
> x2_df<-as.data.frame(matrix(x2,ncol=2,byrow=TRUE)) > x2_df输出结果
V1 V2 1 Grp1 5 2 Grp1 5 3 Grp1 5 4 Grp1 5 5 Grp1 5 6 Grp1 5 7 Grp1 5 8 Grp1 5 9 Grp1 5 10 Grp1 5 11 Grp2 11 12 Grp2 11 13 Grp2 11 14 Grp2 11 15 Grp2 11 16 Grp2 11 17 Grp2 11 18 Grp2 11 19 Grp2 11 20 Grp2 11
范例3
将x3转换为数据帧-
> x3<-c(rep(c("Grp1",rnorm(1),rpois(1,10)),times=10),rep(c("Grp2",rnorm(1),rpois(1,2)),times=10)) > x3输出结果
[1] "Grp1" "0.756362500132569" "4" [4] "Grp1" "0.756362500132569" "4" [7] "Grp1" "0.756362500132569" "4" [10] "Grp1" "0.756362500132569" "4" [13] "Grp1" "0.756362500132569" "4" [16] "Grp1" "0.756362500132569" "4" [19] "Grp1" "0.756362500132569" "4" [22] "Grp1" "0.756362500132569" "4" [25] "Grp1" "0.756362500132569" "4" [28] "Grp1" "0.756362500132569" "4" [31] "Grp2" "-0.339861988439845" "1" [34] "Grp2" "-0.339861988439845" "1" [37] "Grp2" "-0.339861988439845" "1" [40] "Grp2" "-0.339861988439845" "1" [43] "Grp2" "-0.339861988439845" "1" [46] "Grp2" "-0.339861988439845" "1" [49] "Grp2" "-0.339861988439845" "1" [52] "Grp2" "-0.339861988439845" "1" [55] "Grp2" "-0.339861988439845" "1" [58] "Grp2" "-0.339861988439845" "1"
例子4
> x3_df<-as.data.frame(matrix(x3,ncol=3,byrow=TRUE)) > x3_df输出结果
V1 V2 V3 1 Grp1 0.756362500132569 4 2 Grp1 0.756362500132569 4 3 Grp1 0.756362500132569 4 4 Grp1 0.756362500132569 4 5 Grp1 0.756362500132569 4 6 Grp1 0.756362500132569 4 7 Grp1 0.756362500132569 4 8 Grp1 0.756362500132569 4 9 Grp1 0.756362500132569 4 10 Grp1 0.756362500132569 4 11 Grp2 -0.339861988439845 1 12 Grp2 -0.339861988439845 1 13 Grp2 -0.339861988439845 1 14 Grp2 -0.339861988439845 1 15 Grp2 -0.339861988439845 1 16 Grp2 -0.339861988439845 1 17 Grp2 -0.339861988439845 1 18 Grp2 -0.339861988439845 1 19 Grp2 -0.339861988439845 1 20 Grp2 -0.339861988439845 1