R 如何从数据帧中的摘要统计信息生成布尔变量?

R 如何从数据帧中的摘要统计信息生成布尔变量?,r,boolean,max,sapply,tapply,R,Boolean,Max,Sapply,Tapply,我想制作一个布尔列,说明每个样本是否为最大值。 我创建了此函数并与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 }

我想制作一个布尔列,说明每个样本是否为最大值。 我创建了此函数并与
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)
tapply(y,f,function(x) round(x,5)==round(max(x),5))

is.max是的,您可以使用
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)
tapply(y,f,function(x) round(x,5)==round(max(x),5))