如何在 R 数据帧中按行平均值划分行值?


为了按行平均值划分 R 数据帧中的行值,我们可以遵循以下步骤 -

  • 首先,创建一个数据帧。
  • 然后,使用 apply 函数根据行平均值划分数据帧行值。

创建数据帧

让我们创建一个数据帧,如下所示 -

 实时演示

> x<-sample(1:50,25)
> y<-sample(1:50,25)
> df<-data.frame(x,y)
> df

执行后,以上脚本将生成以下输出(由于随机性,该输出将在你的系统上有所不同) -

x y
1 42 23
2 2 37
3 6 42
4 34 28
5 50 19
6 41 46
7 35 38
8 33 7
9 32 9
10 47 10
11 3 4
12 25 39
13 11 22
14 31 31
15 45 41
16 10 36
17 8 34
18 26 1
19 44 20
20 21 17
21 19 26
22 4 14
23 30 35
24 20 47
25 29 40

按行平均值划分数据帧行值

使用 apply 函数按行平均值划分 df 的行值 -

 实时演示

> x<-sample(1:50,25)
> y<-sample(1:50,25)
> df<-data.frame(x,y)
> df_new<-t(apply(df,1, function(x) x/mean(x)))
> df_new

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

x y
[1,] 1.2923077 0.70769231
[2,] 0.1025641 1.89743590
[3,] 0.2500000 1.75000000
[4,] 1.0967742 0.90322581
[5,] 1.4492754 0.55072464
[6,] 0.9425287 1.05747126
[7,] 0.9589041 1.04109589
[8,] 1.6500000 0.35000000
[9,] 1.5609756 0.43902439
[10,] 1.6491228 0.35087719
[11,] 0.8571429 1.14285714
[12,] 0.7812500 1.21875000
[13,] 0.6666667 1.33333333
[14,] 1.0000000 1.00000000
[15,] 1.0465116 0.95348837
[16,] 0.4347826 1.56521739
[17,] 0.3809524 1.61904762
[18,] 1.9259259 0.07407407
[19,] 1.3750000 0.62500000
[20,] 1.1052632 0.89473684
[21,] 0.8444444 1.15555556
[22,] 0.4444444 1.55555556
[23,] 0.9230769 1.07692308
[24,] 0.5970149 1.40298507
[25,] 0.8405797 1.15942029

更新于: 2021 年 8 月 13 日

1K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告