通常,当我们将新列添加到现有R数据帧时,该列会添加到列的末尾,但我们可能需要在最前面。这完全取决于我们的易用性,对变量的熟悉程度及其需求。我们可以使用cbind函数在现有R数据帧的前面添加新列。
请看以下数据帧-
ID <-1:20 Class <-rep(c("A","B","C","D"),times=5) df1 <-data.frame(ID,Class) df1
输出结果
ID Class 1 1 A 2 2 B 3 3 C 4 4 D 5 5 A 6 6 B 7 7 C 8 8 D 9 9 A 10 10 B 11 11 C 12 12 D 13 13 A 14 14 B 15 15 C 16 16 D 17 17 A 18 18 B 19 19 C 20 20 D
现在假设我们想在数据框的前面添加一个新的列Score,那么可以如下所示进行操作-
Score <-sample(1:100,20) df1 <-cbind(Score,df1) df1
输出结果
Score ID Class 1 87 1 A 2 99 2 B 3 90 3 C 4 13 4 D 5 100 5 A 6 50 6 B 7 51 7 C 8 89 8 D 9 70 9 A 10 72 10 B 11 36 11 C 12 12 12 D 13 98 13 A 14 93 14 B 15 86 15 C 16 2 16 D 17 35 17 A 18 34 18 B 19 67 19 C 20 44 20 D
让我们看另一个例子-
x1<-rnorm(20) x2<-rnorm(20,1) x3<-rnorm(20,5) df2<-data.frame(x1,x2,x3) df2
输出结果
x1 x2 x3 1 -0.78695273 -0.16032953 7.353717 2 0.42981155 1.43909343 3.984902 3 -0.37641622 1.20485374 5.290978 4 -1.21622907 0.30081866 6.565326 5 1.02927851 0.07337432 4.152882 6 0.43039700 -0.01348238 6.327660 7 -1.24557402 1.60498706 5.477046 8 -0.60272849 2.73440013 5.185251 9 0.66006939 0.65014947 5.253295 10 2.05074953 2.19918551 7.592227 11 0.49080818 2.02390100 6.074347 12 -1.73147942 0.95372485 3.403098 13 0.71088366 2.38650843 4.912411 14 0.01382291 -1.19527272 5.360768 15 -1.40104160 0.87244309 4.120040 16 1.25912367 -0.31699684 1.676665 17 -0.12747752 -0.42693514 4.532485 18 -0.72938651 1.87944163 5.431540 19 -1.21136136 1.39399158 4.396011 20 0.59961974 1.68892548 5.674447
y<-rpois(20,2) df2<-cbind(y,df2) df2
输出结果
y x1 x2 x3 1 3 -0.78695273 -0.16032953 7.353717 2 2 0.42981155 1.43909343 3.984902 3 1 -0.37641622 1.20485374 5.290978 4 4 -1.21622907 0.30081866 6.565326 5 2 1.02927851 0.07337432 4.152882 6 1 0.43039700 -0.01348238 6.327660 7 3 -1.24557402 1.60498706 5.477046 8 1 -0.60272849 2.73440013 5.185251 9 2 0.66006939 0.65014947 5.253295 10 4 2.05074953 2.19918551 7.592227 11 5 0.49080818 2.02390100 6.074347 12 0 -1.73147942 0.95372485 3.403098 13 1 0.71088366 2.38650843 4.912411 14 3 0.01382291 -1.19527272 5.360768 15 2 -1.40104160 0.87244309 4.120040 16 1 1.25912367 -0.31699684 1.676665 17 3 -0.12747752 -0.42693514 4.532485 18 3 -0.72938651 1.87944163 5.431540 19 2 -1.21136136 1.39399158 4.396011 20 2 0.59961974 1.68892548 5.674447