# chi-squared for two rasters in R

I am kind of new with statistics. I have two raster with categorical values and I want to get chi-square. How can I do this using R? Rasters have the same region and same resolution. Is chi-square the right choice for the computation of variance by ranks?

• Could you elaborate on what you mean by "computation of variance by ranks"? That seems almost wholly unrelated to a chi-squared statistic. – whuber Mar 25 '15 at 0:44
• I want to see whether distributions of categorical variables differ from one another. I have the two rasters (independent and not independent variable). Basically I want to see the differences between them. – geo_dd Mar 25 '15 at 7:41
• The chi-square test, as usually applied, does not address that question: it assesses whether the distributions are independent. Moreover, because data in individual cells in rasters are usually strongly interdependent, the p-value from just about any test will be invalid. How to proceed depends on what these data mean, how they were measured, how they were converted to raster representation, and what you really want to find out. – whuber Mar 25 '15 at 14:22

## 1 Answer

It seems to be a question not so related to GIS, that is since you are treating the raster as a "list" (or a vector) of values. Anyhow you can use the following workflow in R: Assume you have raster objects called r1 and r2.

``````>r1Vals<-getValues(r1);r2Vals<-getValues(r2) # Extract values of r1 and r2 cells to verctors
>r1Vals<-as.facotr(r1Vals);r2Vals<-as.factor(r2Vals) # Convert values to factor (categorial)
>chisq(r1,r2) # Preforms Pearson's chi-square test
``````

I suggest further reading on thge r functions: getValues of the raster package; chisq of the stats package; and the factor object from the base package. In addition - it is reccomended to get help about the right statistical test and its validity to your data in Cross-Validate foroum.