2

每当值在cus0-1 之间时,计算相应的平均值cor并返回结果,对 2-3,3-4,5-6,7-8 执行相同的操作。没有将数据值分配为 NA。

1-阅读corr

conne <- file("C:\\corr.bin","rb")
corr <- readBin(conne, numeric(), size=4, n=1440*720, signed=TRUE)
#please assume a matrix of 720*1440 dimnsions

2-阅读cus

conne1 <- file("C:\\use.bin","rb")
cus <- readBin(conne1, numeric(), size=4, n=1440*720, signed=TRUE)
#please assume a matrix of 720*1440 dimnsions
4

1 回答 1

1

怎么用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
于 2013-06-10T15:33:42.147 回答