I want to match a kernel density layer's {ks} raster dimensions to kriged surface {spatial} and have run into an error. The code demonstrates:
require(ks)
require(raster)
require(spatial)
data(topo, package="MASS")
topo.kr = surf.gls(2, expcov, topo, d=0.7)
krig_ras = raster(prmat(topo.kr, 0, 6.5, 0, 6.5, 50))
kd = kde(topo[,1:2])
kde_ras = raster(kd) # works ok
par(mfrow = c(1, 2))
plot(krig_ras); title('krig')
plot(kde_ras); title('kde')
As you can see the dimensions don't match as kde has added a border (see also setMinMax(krig_ras); setMinMax(kde_ras)). But we can specify eval.points:
pts = as.data.frame(krig_ras, xy=TRUE)
kd2 = kde(topo[,1:2], eval.points = pts[,1:2])
kde_ras2 = raster(kd2)
The last returns the error:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘raster’ for signature ‘"numeric"’
This R-sig-geo page seems to cover the same error, but I can't figure out if this is the same cause - numeric layerNames. Looking at the names/str for kd2 doesn't suggest anything. Grateful for assistance.
If I understand, you would like something like that:
kde_ras2 <- krig_ras
kde_ras2 <- setValues(kde_ras2, kd2$estimate)
Related
I am using library(SuperpixelImageSegmentation) to segmenting my image with associated coordinate NZTM. I would like to save get the segment results as a raster/vector file with associated coordinate NZTM.
When I run my script as below, it has error " Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘writeRaster’ for signature ‘"array", "character"". How to fix it?
library(SuperpixelImageSegmentation)
library(OpenImageR)
library(sp)
library(raster)
library(rgdal)
memory.limit(size=800000)
path = 'C:/Data/SLICO/image.tif'
im = OpenImageR::readImage(path)
init = Image_Segmentation$new()
spx = init$spixel_segmentation(input_image = im,
superpixel =400,
AP_data = TRUE,
use_median = TRUE,
sim_wL = 3,
sim_wA = 10,
sim_wB = 10,
sim_color_radius = 10,
verbose = TRUE)
str(spx)
OpenImageR::imageShow(spx$AP_image_data)
b=writeRaster(spx$AP_image_data, filename='C:/Data/test.tif', format="GTiff", overwrite=TRUE)
I have some code that loops over a list of study IDs (ids) and turns them into separate polygons/spatial points. On the first execution of the loop it produces the following error:
Error in (function (x) : attempt to apply non-function
This is from the raster::rasterToPoints function. I've looked at the examples in the help section for this function and passing fun=NULL seems to be an acceptable method (filters out all NA values). All the values are equal to 1 anyways so I tried passing a simple function like it suggests such as function(x){x==1}. When this didn't work, I also tried to just suppress the error message but without any luck using try() or tryCatch().
Main questions:
1. Why does this produce an error at all?
2. Why does it only display the error on the first run through the loop?
Reproducible example:
library(ggplot2)
library(raster)
library(sf)
library(dplyr)
pacific <- map_data("world2")
pac_mod <- pacific
coordinates(pac_mod) <- ~long+lat
proj4string(pac_mod) <- CRS("+init=epsg:4326")
pac_mod2 <- spTransform(pac_mod, CRS("+init=epsg:4326"))
pac_rast <- raster(pac_mod2, resolution=0.5)
values(pac_rast) <- 1
all_diet_density_samples <- data.frame(
lat_min = c(35, 35),
lat_max = c(65, 65),
lon_min = c(140, 180),
lon_max = c(180, 235),
sample_replicates = c(38, 278),
id= c(1,2)
)
ids <- all_diet_density_samples$id
for (idnum in ids){
poly1 = all_diet_density_samples[idnum,]
pol = st_sfc(st_polygon(list(cbind(c(poly1$lon_min, poly1$lon_min, poly1$lon_max, poly1$lon_max, poly1$lon_min), c(poly1$lat_min, poly1$lat_max, poly1$lat_max, poly1$lat_min, poly1$lat_min)))))
pol_sf = st_as_sf(pol)
x <- rasterize(pol_sf, pac_rast)
df1 <- raster::rasterToPoints(x, fun=NULL, spatial=FALSE) #ERROR HERE
df2 <- as.data.frame(df1)
density_poly <- all_diet_density_samples %>% filter(id == idnum) %>% pull(sample_replicates)
df2$density <- density_poly
write.csv(df2, paste0("pol_", idnum, ".csv"))
}
Any help would be greatly appreciated!
These are error messages, but not errors in the strict sense as the script continues to run, and the results are not affected. They are related to garbage collection (removal from memory of objects that are no longer in use) and this makes it tricky to pinpoint what causes it (below you can see a slightly modified example that suggests another culprit), and why it does not always happen at the same spot.
Edit (Oct 2022)
These annoying messages
Error in x$.self$finalize() : attempt to apply non-function
Error in (function (x) : attempt to apply non-function
Will disappear with the next release of Rcpp, which is planned for Jan 2023. You can also install the development version of Rcpp like this:
install.packages("Rcpp", repos="https://rcppcore.github.io/drat")
I have given the code that the rules are generated.I would like to create an item frequency histogram plot but ıt didn't work.
library(arules)
library(arulesViz)
library(rattle)
x <- read.table("C:/Users/toshıba pc/Desktop/Kitap2.csv", header = TRUE, sep = ";")
y <- as.matrix(x)
rules <- apriori(y, parameter = list(supp = 0.1, conf = 0.8))
itemFrequencyPlot(rules, support = 0.1, cex.names = 0.8)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘itemFrequencyPlot’ for signature ‘"rules"’
itemFrequencyPlot is not defined for rules. You can use
itemFrequencyPlot(items(rules))
to get the frequency of the items in the rules, but I am not sure that this will give you the results you want.
I want to install the RGBL package in bioconductor to perform some graph algorithms.
I updated R to the latest version 3.2.0, and installed the package as instructed on http://www.bioconductor.org/
source("http://bioconductor.org/biocLite.R")
biocLite("RBGL")
It was installed successfully, then I tried to run
library(graph)
library(RBGL)
x<- strongComp(graph)
and returns this error
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘isDirected’ for signature ‘"igraph"’
Here's the traceback
> traceback()
4: stop(gettextf("unable to find an inherited method for function %s for signature %s",
sQuote(fdef#generic), sQuote(cnames)), domain = NA)
3: (function (classes, fdef, mtable)
{
methods <- .findInheritedMethods(classes, fdef, mtable)
if (length(methods) == 1L)
return(methods[[1L]])
else if (length(methods) == 0L) {
cnames <- paste0("\"", vapply(classes, as.character,
""), "\"", collapse = ", ")
stop(gettextf("unable to find an inherited method for function %s for signature %s",
sQuote(fdef#generic), sQuote(cnames)), domain = NA)
}
else stop("Internal error in finding inherited methods; didn't return a unique method",
domain = NA)
})(list("igraph"), function (object)
standardGeneric("isDirected"), <environment>)
2: isDirected(g)
1: strongComp(graph)
My system is Windows 32-bit.
I'm not sure if this is enough information. Please let me know if any other information needed.
Any ideas are appreciated, thanks!
EDIT:
I used the igraph packaged to create the graph object from an edge list with weight
library(igraph)
graph<- graph.data.frame(edge.list[,c(2:4)],directed=TRUE)
I'm not very good with generating random number, here's a reproducible example for my graph
set.seed(123)
edge.list<-cbind(seq(10),c(1,1,2,3,3,4,5,5,5,5),c(2,2,3,5,4,3,4,4,4,2),
runif(10, 1, 30))
colnames(edge.list) <-c("ID","V1","V2","weight")
As pointed out in the comments, you need to make a graph object, not an igraph object.
Here's how I might transform your edge.list into the form that graph expects.
rawEL <- data.frame(source = as.character(edge.list[,1]),
edges = as.character(edge.list[,2]),
weights = edge.list[,3], stringsAsFactors=F
)
V <- unique(c(rawEL$source, rawEL$edges))
edL <- lapply(
split(
rawEL[,-1],
factor(edge.list[,1], levels=V)
), as.list
)
gr <- graphNEL(V, edL, "directed")
plot(gr)
I'm trying to use this code, adapted from dataset meuse
data<-list(var1,var2,x,y)
coordinates(data)=~x+y
grid = spsample(data, type = "regular", cellsize = c(0.05,0.05))
vt <- variogram(var1 ~ var2,data=data)
vt.fit <- fit.variogram(vt, vgm(0.2, "Sph", 800, 0.05))
gstatobj <- gstat(id = 'var1', formula = var1 ~ var2, model=vt.fit, set = list(gls=1))
My goal is creating a grid, like meuse.grid. But coordinates doesn't work... list isn't the right command.
What shall I use?
Is correct the way I'm using to create the grid?
the following reproducible example shows jlhoward's comment is right, and Darko's reply is wrong:
library(gstat)
var1 = 1:3; var2 = 1:3; x = 1:3; y = 1:3
data<-list(var1,var2,x,y)
coordinates(data) = ~x+y
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘coordinates<-’ for signature ‘"list"’
data<-data.frame(var1,var2,x,y)
coordinates(data) = ~x+y
class(data)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"
you may have been confused by doing this again, which would give:
coordinates(data) = ~x+y
Error in `coordinates<-`(`*tmp*`, value = ~x + y) :
setting coordinates cannot be done on Spatial objects, where they have already been set
but leaves the existing (and correct) data in tact.