怎么用data.table
。我假设其中的值cus
实际上是 1:7(所以基本上不确定你为什么需要cusBreak
)。我们创建一个变量来计算用于查找每个组的像素数(如果您的数据中有 NA,mean
请不要忘记包括在内):na.rm
require( data.table )
DT <- data.table( "Cus" = as.vector(cus) , "Corr" = as.vector(corr) )
DT[ , Pix:=( ifelse( is.na( DT$Corr ) , 0 , 1 ) ) ]
DT[ , list( "Mean" = mean(Corr,na.rm=TRUE) , "Sum" = sum(Pix) ) , by = Cus ]
玩具数据的可重现示例
# Data
set.seed(12345)
corr <- matrix( rnorm(16) , 4 )
cus <- matrix( sample(0:7,16,repl=T) , 4 )
cus
# [,1] [,2] [,3] [,4]
#[1,] 1 6 6 2
#[2,] 5 7 3 2
#[3,] 2 4 7 0
#[4,] 2 1 6 0
# Create data.table
DT <- data.table( "Cus" = as.vector(cus) , "Corr" = as.vector(corr) )
# Order by Cus
setkey(DT,Cus)
# Variable to count pixels
DT[ , Pix:=( ifelse( is.na( DT$Corr ) , 0 , 1 ) ) ]
# Get meean of corr grouped by cus
DT[ , list( "Mean" = mean(Corr , na.rm = TRUE ) , "Sum" = sum(Pix) ) , by = Cus ]
# Cus Mean Pixels
#1: 1 0.15467236 2
#2: 5 0.70946602 1
#3: 2 0.08201096 4
#4: 6 0.71301325 3
#5: 7 -0.96710189 2
#6: 4 0.63009855 1
#7: 3 -0.91932200 1
#8: 0 0.03318392 2