【问题标题】:How to make a boolean variable from a summary statistic in a dataframe?如何从数据框中的汇总统计信息中创建布尔变量?
【发布时间】:2014-02-12 21:58:05
【问题描述】:

我想创建一个布尔列来说明每个样本是否为最大值。 我做了这个函数,并与tapply一起使用:

is.max <- function(x){
  x <- data.frame(x)
  x$x <- round(x$x,5)
  x_max <- round(max(x),5)
  for(i in 1:nrow(x)) {
    if(x$x[i] == x_max) x$is.max[i] <- T
    else x$is.max[i] <- F
  }
return(x$is.max)
}

y <- c(rnorm(10), runif(10), rnorm(10,1))
f <- gl(3,10)
m <- tapply(y,f,is.max)

但是有没有更好、更有效的方法来做到这一点?

{附注实际上,我使用了我的真实数据sapply,例如is.maxes&lt;-sapply(s, function(x) is.max(x[,"Sum"]),simplify=F)}

【问题讨论】:

    标签: r boolean max sapply tapply


    【解决方案1】:

    是的,您可以在一行中使用 tapply

    tapply(y,f,function(x) round(x,5)==round(max(x),5))
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2014-04-09
      • 2015-07-31
      • 2018-05-21
      • 2013-12-27
      • 2022-12-06
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多