行值的平均值可以通过使用dplyr包的按行函数以及mutate函数在数据帧中添加均值的新列来找到。逐行函数实际上帮助R逐行读取数据帧中的值,然后我们可以使用均值函数来找到均值,如以下示例所示。
请看以下数据帧:
> x1<-rpois(20,1) > x2<-rpois(20,5) > df1<-data.frame(x1,x2) > df1
输出结果
x1 x2 1 0 8 2 2 3 3 2 5 4 0 5 5 3 2 6 0 10 7 3 5 8 1 7 9 0 4 10 1 6 11 1 2 12 1 6 13 1 1 14 0 7 15 3 3 16 1 5 17 0 5 18 0 4 19 0 7 20 0 8
加载dplyr包并找到数据帧df1的行值的平均值:
> library(dplyr) > df1%>%rowwise()%>%mutate(Mean=mean(c(x1,x2))) # A tibble: 20 x 3 # Rowwise:
输出结果
x1 x2 Mean <int><int><dbl> 1 0 8 4 2 2 3 2.5 3 2 5 3.5 4 0 5 2.5 5 3 2 2.5 6 0 10 5 7 3 5 4 8 1 7 4 9 0 4 2 10 1 6 3.5 11 1 2 1.5 12 1 6 3.5 13 1 1 1 14 0 7 3.5 15 3 3 3 16 1 5 3 17 0 5 2.5 18 0 4 2 19 0 7 3.5 20 0 8 4
> y1<-rnorm(20) > y2<-rnorm(20,0.05) > y3<-rnorm(20,0.5,0.0025) > df2<-data.frame(y1,y2,y3) > df2
输出结果
y1 y2 y3 1 1.904146103 -1.010755257 0.4977748 2 -0.659153462 0.757833514 0.5000584 3 -1.349287399 0.035455534 0.4995245 4 1.251468999 -0.770912867 0.5023573 5 0.558542205 0.938371389 0.5037919 6 -1.088022365 -0.676129238 0.5024196 7 0.777812404 -0.649474781 0.4978783 8 -0.070005581 1.296222134 0.4989934 9 0.955297951 -0.010204761 0.5009613 10 -1.027516169 0.688293380 0.4995052 11 -0.004430055 1.095789444 0.5038756 12 -0.487932801 1.891399000 0.5006688 13 2.552820247 -0.240468655 0.4998481 14 -0.202030666 0.990596084 0.5025346 15 0.275771430 1.274736854 0.4984426 16 -0.541683198 1.056570340 0.4992698 17 -0.468355466 -1.878586227 0.4999905 18 0.031146373 0.009999742 0.5042049 19 0.608943200 -1.306773821 0.5030888 20 0.299916589 -0.759283709 0.5013502
查找数据帧df2的行值的平均值:
> df2%>%rowwise()%>%mutate(Mean=mean(c(y1,y2,y3))) # A tibble: 20 x 4 # Rowwise:
输出结果
y1 y2 y3 Mean <dbl><dbl><dbl><dbl> 1 1.90 -1.01 0.498 0.464 2 -0.659 0.758 0.500 0.200 3 -1.35 0.0355 0.500 -0.271 4 1.25 -0.771 0.502 0.328 5 0.559 0.938 0.504 0.667 6 -1.09 -0.676 0.502 -0.421 7 0.778 -0.649 0.498 0.209 8 -0.0700 1.30 0.499 0.575 9 0.955 -0.0102 0.501 0.482 10 -1.03 0.688 0.500 0.0534 11 -0.00443 1.10 0.504 0.532 12 -0.488 1.89 0.501 0.635 13 2.55 -0.240 0.500 0.937 14 -0.202 0.991 0.503 0.430 15 0.276 1.27 0.498 0.683 16 -0.542 1.06 0.499 0.338 17 -0.468 -1.88 0.500 -0.616 18 0.0311 0.0100 0.504 0.182 19 0.609 -1.31 0.503 -0.0649 20 0.300 -0.759 0.501 0.0140