繁体   English   中英

在R中,我如何优雅地计算多列的中位数,然后计算每行中超过中位数的单元格数?

[英]In R, how can I elegantly compute the medians for multiple columns, and then count the number of cells in each row that exceed the median?

假设我有以下数据框:

Base Coupled Derived Decl
   1       0       0    1
   1       7       0    1
   1       1       0    1
   2       3      12    1
   1       0       4    1

这里是dput输出:

temp <- structure(list(Base = c(1L, 1L, 1L, 2L, 1L), Coupled = c(0L,7L, 1L, 3L, 0L), Derived = c(0L, 0L, 0L, 12L, 4L), Decl = c(1L, 1L, 1L, 1L, 1L)), .Names = c("Base", "Coupled", "Derived", "Decl"), row.names = c(NA, 5L), class = "data.frame")

我想计算每列的中位数。 然后,对于每一行,我想计算大于其各自列的中位数的单元格值的数量,并将其作为名为AboveMedians的列附加。

在这个例子中,中位数是c(1,1,0,1) 我想要的结果表是

Base Coupled Derived Decl AboveMedians
   1       0       0    1            0
   1       7       0    1            1
   1       1       0    1            0
   2       3      12    1            3
   1       0       4    1            1

优雅的R方式是什么? 我有一些涉及for循环和sapply的东西,但这似乎不是最佳的。

谢谢。

我们可以使用rowMediansmatrixStats转换后data.framematrix

library(matrixStats)
Medians <- colMedians(as.matrix(temp))
Medians
#[1] 1 1 0 1

然后,复制'Medians'以使尺寸等于'temp'的尺寸,进行比较并获得逻辑矩阵上的rowSums

temp$AboveMedians <- rowSums(temp >Medians[col(temp)])
temp$AboveMedians
#[1] 0 1 0 3 1

或者只有base R选项

 apply(temp, 2, median)
 # Base Coupled Derived    Decl 
 #   1       1       0       1 

 rowSums(sweep(temp, 2, apply(temp, 2, median),  FUN = ">"))

另一种选择:

library(dplyr)
library(purrr)

temp %>% 
  by_row(function(x) {
    sum(x > summarise_each(., funs(median))) }, 
    .to = "AboveMedian", 
    .collate = "cols"
    )

这使:

#Source: local data frame [5 x 5]
#
#   Base Coupled Derived  Decl AboveMedian
#  <int>   <int>   <int> <int>       <int>
#1     1       0       0     1           0
#2     1       7       0     1           1
#3     1       1       0     1           0
#4     2       3      12     1           3
#5     1       0       4     1           1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM