简体   繁体   English

如何计算R中文件的像素数?

[英]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. 每当cus值介于0-1之间时,计算cor的相应平均值并返回结果,请对2-3、3-4、5-6、7-8进行相同的操作。没有将数据值分配为NA 。

1- to read corr : 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- to read cus : 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

How about using data.table . 如何使用data.table I am assuming that the values in cus are actually 1:7 (so basically not sure why you need cusBreak ). 我假设中的值cus实际上是1:7(所以基本上不知道为什么你需要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): 我们创建一个变量来计算用于查找每个组mean的像素数(如果您的数据中包含NA,请不要忘记添加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 ]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM