如何在R数据帧中按行查找变量总和?
为了按行查找变量的总和,我们指的是数据帧中行值的总和。借助rowSums函数可以轻松完成此操作。例如,如果我们有一个名为df的数据帧,则可以使用以下命令找到按行的变量总和-
rowSums(df)
例1
考虑以下数据帧-
> x1<-rpois(20,2) > x2<-rpois(20,2) > x3<-rpois(20,2) > df1<-data.frame(x1,x2,x3) > df1输出结果
x1 x2 x3 1 0 2 3 2 1 0 1 3 1 0 2 4 3 3 2 5 4 2 2 6 3 1 5 7 2 2 1 8 4 2 2 9 2 4 0 10 3 1 5 11 3 1 2 12 0 3 1 13 2 3 0 14 1 1 0 15 1 1 1 16 3 1 0 17 1 2 1 18 1 0 2 19 4 2 1 20 0 2 3
在df1中查找数据的行总和-
> df1$x_total<-rowSums(df1) > df1输出结果
x1 x2 x3 x_total 1 0 2 3 5 2 1 0 1 2 3 1 0 2 3 4 3 3 2 8 5 4 2 2 8 6 3 1 5 9 7 2 2 1 5 8 4 2 2 8 9 2 4 0 6 10 3 1 5 9 11 3 1 2 6 12 0 3 1 4 13 2 3 0 5 14 1 1 0 2 15 1 1 1 3 16 3 1 0 4 17 1 2 1 4 18 1 0 2 3 19 4 2 1 7 20 0 2 3 5
例2
> y1<-rnorm(20) > y2<-rnorm(20) > y3<-rnorm(20) > df2<-data.frame(y1,y2,y3) > df2输出结果
y1 y2 y3 1 0.59017486 -0.1196278 0.822573265 2 -1.12831016 0.7454030 0.173110462 3 0.65838766 -0.4798106 0.700891619 4 -3.09790550 -0.4401321 0.343264756 5 -0.27170928 -0.8106993 -0.658724220 6 1.51823786 0.1162130 -0.145487501 7 1.66852069 -0.4254530 -0.372181307 8 0.39011721 1.7260926 -0.253079767 9 0.12034466 0.4142485 -0.547526473 10 0.73264687 0.3537576 -0.248502362 11 -1.19683499 1.0923578 0.139092087 12 -0.02475713 -0.7436116 1.154820901 13 -1.68760189 -1.1306767 -0.002655384 14 -0.56164347 0.6580410 1.831938297 15 0.26013745 -0.6617675 -1.398981829 16 0.68685167 -1.2256218 0.435335557 17 -0.01735620 1.2882963 -0.378027363 18 -0.86458207 1.6013430 0.567320925 19 0.15593632 0.7086373 -0.231115639 20 0.54771681 1.8800467 0.235589089
在df2中找到数据的行总和-
> df2$y_total<-rowSums(df2) > df2输出结果
y1 y2 y3 y_total 1 0.59017486 -0.1196278 0.822573265 1.29312029 2 -1.12831016 0.7454030 0.173110462 -0.20979674 3 0.65838766 -0.4798106 0.700891619 0.87946873 4 -3.09790550 -0.4401321 0.343264756 -3.19477280 5 -0.27170928 -0.8106993 -0.658724220 -1.74113281 6 1.51823786 0.1162130 -0.145487501 1.48896334 7 1.66852069 -0.4254530 -0.372181307 0.87088643 8 0.39011721 1.7260926 -0.253079767 1.86313004 9 0.12034466 0.4142485 -0.547526473 -0.01293328 10 0.73264687 0.3537576 -0.248502362 0.83790209 11 -1.19683499 1.0923578 0.139092087 0.03461487 12 -0.02475713 -0.7436116 1.154820901 0.38645212 13 -1.68760189 -1.1306767 -0.002655384 -2.82093399 14 -0.56164347 0.6580410 1.831938297 1.92833585 15 0.26013745 -0.6617675 -1.398981829 -1.80061190 16 0.68685167 -1.2256218 0.435335557 -0.10343459 17 -0.01735620 1.2882963 -0.378027363 0.89291278 18 -0.86458207 1.6013430 0.567320925 1.30408187 19 0.15593632 0.7086373 -0.231115639 0.63345799 20 0.54771681 1.8800467 0.235589089 2.66335255