Number of cells of raster under a condition [closed] - r

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I have a binary raster file and I want to count the number of pixels with value one. How do I do that with R?

Ben Bolker's solution, but then with terra (the replacement for raster)
set.seed(101)
library(terra)
r <- rast(matrix(sample(0:1,size=10000,replace=TRUE),100))
global(r, sum)
# sum
#lyr.1 4984
To count the number of 1s in non-binary rasters, and considering NAs, I would prefer
global(r==1, sum, na.rm=TRUE)
over
global(r, function(x) sum(x==1, na.rm=TRUE))
Because the former also works on very large rasters, as "sum" is a known function that can be computed in chunks.

There may well be a more efficient way to do this, but:
set.seed(101)
library(raster)
r <- raster(matrix(sample(0:1,size=10000,replace=TRUE),100))
cellStats(r,function(x,...) sum(x==1)) ## 4984
Actually, if this is a binary raster, cellStats(r, sum) works just as well (and probably quicker?)

Related

Create a plot from boxplot.stats [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Someone sent me a file containing the list of boxplot.stats.
I now want to reproduce and plot this boxplot from the list. (I have stats, n , conf and out).
How should I proceed? Can I use plotly for this purpose?
So I have the following list
stats
[1] -0.30518460 0.08578944 0.28487839 0.34645644 0.73711925
n
[1] 3472096
conf
[1] 0.2846574 0.2850994
out
[1] -2.5168701 -0.3115725 0.7683801 1.9771345 -0.5612497 -1.0996948
And my output should be boxplot with the values above.
If by boxplot.stats you mean the list of values boxplot normally produces, you can use bxp to plot.
x <- boxplot(rnorm(100))
bxp(x)
The boxplot.stats function does the computation for boxplot, but doesn't work with bxp directly.
bxp(boxplot.stats(rnorm(100)))
Error in z$stats[, i] : incorrect number of dimensions
If you do just have the output from boxplot.stats, you can hack out a solution by converting each of the list elements to a 1 column matrix:
bxp(lapply(boxplot.stats(rnorm(100)),as.matrix,1))

How to construct matrices/vectors from a table in R? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm quite new to R, and if I imported a .csv file and if rows represent
time and columns represent n variables of interest, how could I construct a
function that returns any given 1xn vector from the table?
P.S. I'm not just interested in constructing a vector, but I will perform
matrix algebra with iterative calculations to estimate parameters, which means
I will need to use a for-loop.
If the data structure contains e.g. m rows and n columns i.e. n variables, you can easily construct the n vectors without much effort.
data<-read.csv(".../file.csv")
class(data)
[1] "data.frame"
class(as.numeric(data[1,]))
[1] "numeric"
So it is not a big deal to convert 1*n matrix i.e. vector of length(ncol(data)).
In a loop just use
data["required Row Number",]
to access the particular row. Each case it will ultimately give 1*n matrix or a vector of length(n)
You can use the function melt() from the package reshape2
Or if you want to use the for loop, try something like:
one_col <- data[,1]
for (i in 2:ncol(data)){
one_col <- rbind(one_col, data[,i])
}

Faster method for aggregating this data in R [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a fairly large dataset (6.5 M rows, 8 cols) that I'm summarizing in a time series of aggregate counts of observations by day.
I'm currently summing across the intersection of two vectors that are the axes in my time series matrix. The iterations are taking hours to run, and I'm wondering if I'm overlooking something that might give better performance.
My code:
m<-length(datespace)
sensorlist<-as.vector(unique(sensordata$SOURCE))
n<-length(sensorlist)
y <- matrix(0, nrow=m, ncol=n)
colnames(y) <- sensorlist
for(sensor in 1:n){
for(date in 1:m){
count<-sum(as.vector(sensordata$SOURCE==sensorlist[sensor] & di==datespace[date]))
y[date,sensor] = count
}
}
I know FOR loops are less efficient are an indicator that there's probably a better way in R to get this done.
The crux of this problem seems to be a fast way to create a sparse matrix that fills in the missing summary data with zeros.
Pretty sure this is a simple tally:
library(dplyr)
sensordata %>%
group_by(SOURCE) %>% # or maybe group_by(SOURCE, di)?
tally()

Sliding window using R [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a data frame with daily data in R (148 columns by 6230 rows). I want to find the correlations coefficients using sliding windows with length of 600 (days) with windows displacement of 5 (days) and trying to generate 1220 correlation matrices (approx.). All the examples that I saw used only one information vector. There exist an easy way to find those correlation matrices using sliding window? I'll appreciate any suggestion.
If M is the input matrix then each row of out is one correlation matrix strung out column by column:
library(zoo)
out <- rollapply(M, 600, by = 5, function(x) c(cor(x)), by.column = FALSE)
They could be reshaped into a list of correlation matrices, if need be:
L <- lapply(1:nrow(out), function(i) matrix(out[i, ], ncol(M)))
or as an array:
simplify2array(L)

Basic matrix math in R [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I want to perform basic math using two matrices.
As my input I have two 3x3 matrices. I would like to divide every integer in matrixA by every integer in matrixB and the output to be one 3x3 matrix of their products.
What is the R function(s) that can do that for me.
Thanks in advance!
It sounds like you want to divide element by element. In this case, you can simply use the / operator.
### Create two matrices
matA <- matrix(1:9, nrow = 3)
matB <- matA
### Divide element by element
matB / matA
### As Frank pointed out, division by 0 goes to Inf
matA[1, 1] <- 0
matB / matA

Resources