如何在R数据框中查找每列的值的log2,即使某些列是分类变量?
要在R数据框中查找每列值的log2,即使某些列是分类变量,我们可以按照以下步骤操作:
首先,创建一个数据框。
然后,使用plyr包中的numcolwise函数来查找log2,即使某些列是分类变量。
示例
创建数据框
让我们创建一个如下所示的数据框:
Level<-sample(c("low","medium","high"),25,replace=TRUE) Group<-sample(c("first","second"),25,replace=TRUE) Score<-sample(1:50,25) Demand<-sample(1:100,25) df<-data.frame(Level,Group,Score,Demand) df
输出
执行上述脚本后,将生成以下输出(由于随机化,此输出会在您的系统上有所不同):
Level Group Score Demand 1 high first 38 86 2 medium second 44 100 3 medium first 33 68 4 high first 25 24 5 low first 34 62 6 low first 43 55 7 low first 35 42 8 high second 21 92 9 low second 27 78 10 medium first 36 66 11 low first 2 22 12 high first 42 40 13 high second 40 46 14 low first 28 70 15 medium first 23 53 16 medium first 49 58 17 low first 6 31 18 low first 18 79 19 medium second 50 10 20 low first 31 27 21 high second 10 43 22 low second 4 23 23 medium second 20 87 24 high first 12 69 25 high second 15 9
查找log2,即使某些列是分类变量
使用plyr包中的numcolwise函数在数据框df中查找每个数值列的log2:
Level<-sample(c("low","medium","high"),25,replace=TRUE) Group<-sample(c("first","second"),25,replace=TRUE) Score<-sample(1:50,25) Demand<-sample(1:100,25) df<-data.frame(Level,Group,Score,Demand) library(plyr) numcolwise(log2)(df)
输出
Score Demand 1 5.247928 6.426265 2 5.459432 6.643856 3 5.044394 6.087463 4 4.643856 4.584963 5 5.087463 5.954196 6 5.426265 5.781360 7 5.129283 5.392317 8 4.392317 6.523562 9 4.754888 6.285402 10 5.169925 6.044394 11 1.000000 4.459432 12 5.392317 5.321928 13 5.321928 5.523562 14 4.807355 6.129283 15 4.523562 5.727920 16 5.614710 5.857981 17 2.584963 4.954196 18 4.169925 6.303781 19 5.643856 3.321928 20 4.954196 4.754888 21 3.321928 5.426265 22 2.000000 4.523562 23 4.321928 6.442943 24 3.584963 6.108524 25 3.906891 3.169925
广告