要找到R数据帧中行的标准差,我们可以使用dplyr包的mutate函数和matrixStats包的rowSds函数。例如,如果我们有一个名为df的数据框,其中包含两列x和y,则可以使用以下命令找到行的标准差-
df%>%mutate(STDEV=rowSds(as.matrix(.[c("x","y")])))
考虑以下数据帧-
x1<-rpois(20,5) x2<-rpois(20,2) x3<-rpois(20,3) x4<-rpois(20,2) df1<-data.frame(x1,x2,x3,x4) df1输出结果
x1 x2 x3 x4 1 3 5 6 4 2 5 2 2 3 3 9 5 5 2 4 6 4 8 2 5 5 3 3 4 6 3 2 8 3 7 4 3 4 2 8 2 3 4 1 9 9 1 1 3 10 0 6 4 2 11 8 1 5 1 12 5 5 6 5 13 5 1 1 2 14 7 0 2 0 15 6 1 2 1 16 7 0 2 1 17 7 6 3 1 18 6 0 3 2 19 3 3 2 1 20 9 2 3 0
加载dplyr和matrixStats包,并在数据帧df1中查找行的标准偏差-
library(dplyr) library(matrixStats) df1%>%mutate(STDEV=rowSds(as.matrix(.[c("x1","x2","x3","x4")])))输出结果
x1 x2 x3 x4 STDEV 1 3 5 6 4 1.2909944 2 5 2 2 3 1.4142136 3 9 5 5 2 2.8722813 4 6 4 8 2 2.5819889 5 5 3 3 4 0.9574271 6 3 2 8 3 2.7080128 7 4 3 4 2 0.9574271 8 2 3 4 1 1.2909944 9 9 1 1 3 3.7859389 10 0 6 4 2 2.5819889 11 8 1 5 1 3.4034296 12 5 5 6 5 0.5000000 13 5 1 1 2 1.8929694 14 7 0 2 0 3.3040379 15 6 1 2 1 2.3804761 16 7 0 2 1 3.1091264 17 7 6 3 1 2.7537853 18 6 0 3 2 2.5000000 19 3 3 2 1 0.9574271 20 9 2 3 0 3.8729833
y1<-rnorm(20) y2<-rnorm(20,5,3.2) df2<-data.frame(y1,y2) df2输出结果
y1 y2 1 0.86446680 5.6802977 2 0.60195104 0.6486237 3 -1.59813139 2.5848931 4 -0.78227050 3.8482150 5 1.48952658 13.1513324 6 -0.60257914 8.2694503 7 1.18436339 3.0598210 8 0.69717086 7.2714069 9 0.38565158 2.6345042 10 0.66689354 6.7638348 11 -0.28068587 3.3071879 12 0.70508469 7.6279248 13 0.04041801 2.4287727 14 -0.47374539 -1.3595359 15 -1.21819237 4.5158727 16 0.91791874 5.1770052 17 0.78480807 7.1456598 18 -1.07354342 4.2004320 19 0.02830331 6.5698650 20 0.72080430 5.8628232
在数据帧df2中找到行的标准偏差-
df2%>%mutate(STDEV=rowSds(as.matrix(.[c("y1","y2")])))输出结果
y1 y2 STDEV 1 0.86446680 5.6802977 3.40530670 2 0.60195104 0.6486237 0.03300256 3 -1.59813139 2.5848931 2.95784496 4 -0.78227050 3.8482150 3.27424772 5 1.48952658 13.1513324 8.24614194 6 -0.60257914 8.2694503 6.27347216 7 1.18436339 3.0598210 1.32614878 8 0.69717086 7.2714069 4.64868686 9 0.38565158 2.6345042 1.59017895 10 0.66689354 6.7638348 4.31118848 11 -0.28068587 3.3071879 2.53700985 12 0.70508469 7.6279248 4.89518719 13 0.04041801 2.4287727 1.68882179 14 -0.47374539 -1.3595359 0.62634847 15 -1.21819237 4.5158727 4.05459631 16 0.91791874 5.1770052 3.01162894 17 0.78480807 7.1456598 4.49780138 18 -1.07354342 4.2004320 3.72926381 19 0.02830331 6.5698650 4.62558262 20 0.72080430 5.8628232 3.63595643