hyat
hyat

Reputation: 1057

How to count the number of pixels in a file in R?

whenever the values in cus range between 0-1, calculate the corresponding average in cor and return the result, do the same thing with 2-3,3-4,5-6,7-8.no data values are assigned as NA.

1- to read 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- to read 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

Upvotes: 2

Views: 2330

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59980

How about using data.table. I am assuming that the values in cus are actually 1:7 (so basically not sure why you need cusBreak). We create a variable to count the number of pixels used to find the mean of each group (and don't forget to include na.rm if you have NAs in your data):

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 ]

A reproducible example with toy data

#  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

Upvotes: 1

Related Questions