How can I calculate the sd? Error in as.double(x): cannot coerce type 'S4' to vector of type 'double'

ぃ、小莉子 提交于 2020-06-16 06:39:13

问题


Do somebody know what is wrong with my code? I edited the post, because i didn´t give you the data. I want to calculate the sd. The calculation of the mean worked.

Here is the link to the cropped data:

https://drive.google.com/drive/folders/1ljT1fzaDlSmn_3j7zHshS5lrV1wBvVQD

library(raster)
r <- brick("filename")
#mean
mean <- mean(r)

#sd
standard_dev <- sd(r)
standard_dev2 <- sd(r, na.rm =TRUE)
standard_deviation <- calc(r, sd)

回答1:


You want the compute the sd for each cell in a RasterBrick.

Always include a self-contained, minimal reproducible example. You can start with an example in the manual of the package you are using, like this

library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))

Solution

x <- calc(b, sd)

x
class      : RasterLayer 
dimensions : 77, 101, 7777  (nrow, ncol, ncell)
resolution : 1, 1  (x, y)
extent     : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
crs        : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs 
source     : memory
names      : layer 
values     : 0, 38.5746  (min, max)

It seems that this does not work for you because you have a RasterLayer called sd

sd <- b
calc(b, sd)
#Error in (function (classes, fdef, mtable)  : 
#  unable to find an inherited method for function ‘calc’ for signature ‘"RasterBrick", "RasterBrick"’

In that case you can be more explicit and use the functions namespace (stats)

calc(b, stats::sd)

And then it works again as expected




回答2:


Function: sd(x, na.rm = FALSE)

This function computes the standard deviation of the values in x. If na.rm is TRUE then missing values are removed before computation proceeds.

Arguments

x: a numeric vector or an R object but not a factor coercible to numeric by as.double(x).

na.rm: logical. Should missing values be removed?

Example

sd(1:2) ^ 2

Taken from accessing the help documentation in RStudio using:

?sd()

For your situation:

standard_deviation <- sd(r)

We may be able to help you further if you provide us with a reproducible example.



来源:https://stackoverflow.com/questions/62344170/how-can-i-calculate-the-sd-error-in-as-doublex-cannot-coerce-type-s4-to-ve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!