Create empty spatial lines object - r

I am trying to create an empty SpatialLines object. With polygons it is easy:
SpatialPolygons(list())
For spatial lines this does not work:
SpatialLines(LinesList = list())
Error in bb[1, ] : incorrect number of dimensions
SpatialLines(LinesList = Lines(list(),ID = "a"))
Error in as.list.default(X) :
no method for coercing this S4 class to a vector
SpatialLines(LinesList = Lines(slinelist = Line(coords = cbind(x = c(), y = c())), ID = c()))
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘coordinates’ for signature ‘"NULL"’
Does someone know how it I could create an empty SpatialLines object?
Workaround
I found a workaround which is maybe not the best way of doing it. I generates a spatial line with no length:
SpatialLines(list(Lines(Line(coords = cbind(x = c(0,0), y = c(0,0))), ID = "A")))

Interesting Q!
The only way I was able to work around was by creating a dummy line and removing it like this:
sl <- SpatialLines(LinesList = list(Lines(Line(matrix(0, ncol = 2)), ID = NA)))
sl <- sl[0]
length(sl)
# [1] 0
When adding your dummy line the length is returned as 1 as expected:
length(rbind.SpatialLines(sl, SpatialLines(list(Lines(Line(coords = cbind(x = c(0,0),
y = c(0,0))),
ID = "A")))))
# [1] 1

Related

unable to find an inherited method for function 'distance' for signature '"matrix", "character"', but it's a df?

Here is all my code leading up to the function as per #Till request!
library("phyloseq")
library("qiime2R")
library("vegan")
# read in phyloseq objects from qiime
physeq<-qza_to_phyloseq(
features="~/Documents/qiime2-analyses/CRD/fresh_run/table.qza",
tree="~/Documents/qiime2-analyses/CRD/fresh_run/rooted-tree.qza",
"~/Documents/qiime2-analyses/CRD/fresh_run/taxonomy.qza",
metadata = "crd-metadata.txt")
# Clean out unwanted taxa annotations. Base script removes endozoicimonaceae, escherischia,
# and shigella contaminates
physeq <- subset_taxa(physeq, Family!="f__Endozoicimonaceae")
physeq <- subset_taxa(physeq, Family!="f__Enterobacteriaceae")
physeq <- subset_taxa(physeq, Family!="f__mitochondria")
physeq <- subset_taxa(physeq, Class!="c__Chloroplast")
#pull out otu table
otu_table <- (as.data.frame(otu_table(physeq)))
# rotate otu matrix layout
rownames(otu_table) <- factor(rownames(otu_table), levels = rownames(otu_table))
otu_ord <- as.data.frame(t(otu_table[rowSums(otu_table)!=0, ]))
# remove any rows or columns with only 0s
otu_ord <- otu_ord[, colSums(otu_ord !=0)>0]
otu_ord <- otu_ord[rowSums(otu_ord[])>0,]
#edits from observations of this StO chat
rownames(otu_ord) <- gsub("sample-", "", rownames(otu_ord))
rownames(otu_ord) <- as.numeric(rownames(otu_ord))
otu_ord <- as.matrix(otu_ord)
#the args of the function
raup_crick_abundance = function(spXsite=otu_ord, plot_names_in_col1=TRUE,
classic_metric=FALSE, split_ties=TRUE,
reps=9999, set_all_species_equal=FALSE,
as.distance.matrix=TRUE, report_similarity=FALSE){
Please note the whole function is verbatim from Stegen_etal_ISME_2013 github linked below and here.
I am receiving the error
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘distance’ for signature ‘"matrix", "character"’
Called from: (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("matrix", "character"), new("nonstandardGenericFunction",
.Data = function (physeq, method, type = "samples", ...)
{
standardGeneric("distance")
}, generic = "distance", package = "phyloseq", group = list(),
valueClass = character(0), signature = c("physeq", "method",
"type"), default = NULL, skeleton = (function (physeq, method,
type = "samples", ...)
stop("invalid call in method dispatch to 'distance' (no default method)",
domain = NA))(physeq, method, type, ...)), <environment>)
Browse[1]> traceback()
No traceback available
within this function linked here.
My argument is a data.frame (dput() below) with no character strings? As I understand it, the error is saying the function distance () can't be calculated with matrix or character strings, which I agree with...
Therefore, I am unsure why distance () cannot operate with my arg, if I am interpreting the error correctly.
Thank you.
Here is my Qiime2 OTU table.qza linked to this Dropbox file, my rooted tree linked here, and my taxonomy linked here to recreate my phyloseq object.
What the error message is actually trying to get across is that your matrix has character values and the function you called can not handle it. The first column in data.frame is a character column.
If your data frame is called ex_otu_ord, try this:
ex_otu_ord <- ex_otu_ord[-1]
ex_otu_ord <- as.matrix(ex_otu_ord)
Then try again to call the function on ex_otu_ord.

error in t(dat1) and pairwise not found errors in R

Can someone tell me why the Error in t(dat1) : object 'dat1' not found is appearing, and why Error in is.element("pairwise", names(x)) : object 'pwStats' not found is too?
I'm new to R, and I am trying to visualize the Djost graph shown here:
pwStats <-fastDivPart(infile = microsatellitecoyreadyforR,
outfile = "Coyote_resultspwstats",
gp = 2, bs_locus = TRUE,
bs_pairwise = TRUE, boots = 3)
Error in t(dat1) : object 'dat1' not found
#visualize pwStats
diffPlot(x=pwStats,outfile = "Coyote_resultspwstats", interactive=TRUE)
Error in is.element("pairwise", names(x)) : object 'pwStats' not found

Error in shapefile$shp : $ operator is invalid for atomic vectors- DSsim package R

I am trying to add a shapefile, when making a region for the DSsim package in R. But I keep getting the error code- Error in shapefile$shp : $ operator is invalid for atomic vectors. Can anyone help me?
The code I have is as follows:
library(DSsim)
file.path("C:/Users/user/Desktop/Lorna/Distance/WITH VARIABLES/C3p", "C3p.shp")
C3P <- shapefiles::read.shp("C3p.shp")
region.label <- make.region(region.name = "C3P", strata.name = 0, units = "km", area = 51.02, shapefile=("C3p.shp"), check.LinkID = TRUE)
The help for make.region says:
shapefile: a shapefile object of the region loaded into R using
‘read.shapefile(shape.name)’ from the shapefiles library.
but you have done:
region.label <- make.region(...., shapefile=("C3p.shp"), ....)
which is the name of the shapefile, in parentheses (these brackets).
Try using read.shapefiles instead of read.shp:
C3P <- shapefiles::read.shapefile(
"C:/Users/user/Desktop/Lorna/Distance/WITH VARIABLES/C3p"
)
Assuming the path to your shapefile is "C:/Users/user/Desktop/Lorna/Distance/WITH VARIABLES/C3p.shp" and similarly for C3p.shx etc.
and then:
region.label <- make.region(
region.name = "C3P",
strata.name = 0,
units = "km",
area = 51.02,
shapefile=C3P, # the object you created two lines previous
check.LinkID = TRUE)

R error : "attempt to select less than one element in get1index"

I'm a beginner in R and I'm trying to use the package ClonEvol, however the documentation on the github webpage is very limited. So for now I'm using their example code and trying to adapt it to my data called ce.
ce <- data.frame(
cluster = c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7),
gene = c("geneA","geneB","geneC","geneD","geneA","geneB","geneC","geneD","geneA","geneB","geneC","geneD","geneA","geneB","geneC",
"geneD","geneA","geneB","geneC","geneD","geneA","geneB","geneC","geneD","geneA","geneB","geneC","geneD"),
prim.vaf = c(0.5,0,0,0,0.5,0.5,0,0,1,0.5,0,0,1,0.5,0,0.5,0.5,0.5,0,0.5,0.5,0.5,0,1,0.5,0.5,0.5,0)
)
cluster <- ce$cluster
gene <- ce$gene
prim.vaf <- ce$prim.vaf
x <- ce
vaf.col.names <- grep('prim.vaf', colnames(x), value=T)
sample.names <- gsub('prim.vaf', '', vaf.col.names)
x[, sample.names] <- x[, vaf.col.names]
vaf.col.names <- sample.names
sample.groups <- c('P', 'R');
names(sample.groups) <- vaf.col.names
x <- x[order(x$cluster),]
pdf('box.pdf', width = 3, height = 5, useDingbats = FALSE, title='')
pp <- variant.box.plot(x,
cluster.col.name = ce$cluster,
show.cluster.size = FALSE,
cluster.size.text.color = 'blue',
vaf.col.names = vaf.col.names,
vaf.limits = 70,
sample.title.size = 20,
violin = FALSE,
box = FALSE,
jitter = TRUE,
jitter.shape = 1,
jitter.color = clone.colors,
jitter.size = 3,
jitter.alpha = 1,
jitter.center.method = 'median',
jitter.center.size = 1,
jitter.center.color = 'darkgray',
jitter.center.display.value = 'none',
highlight = 'is.driver',
highlight.note.col.name = 'gene',
highlight.note.size = 2,
highlight.shape =16,
order.by.total.vaf = FALSE
)
dev.off()
However, I get the following error :
Error in .subset2(x, i, exact = exact) : recursive indexing failed at level 2
And if I delete cluster.col.name=ce$cluster and vaf.col.names=vaf.col.names, the error becomes the following :
Error in .subset2(x, i, exact = exact) : attempt to select less than one
element in get1index
Has someone any idea of what went wrong ?
I met this error message today. I know little about the R package in this question, but I think I can show what the error message means here. And maybe it is useful for you to find out the problem.
The error occurs when we use NULL as an index to subset a list.
Here are the expressions invoking this error message:
any.list <- list(1, 2, 3)
# If single brackets, no error occurs:
any.list[NULL]
## list()
# If double brackets, the error occurs:
any.list[[NULL]]
## Error in any.list[[NULL]] :
## attempt to select less than one element in get1index
The list above can be any list, or even a vector.
a.vector <- c(1, 2, 3)
a.vector[[NULL]]
## Error in a.vector[[NULL]] :
## attempt to select less than one element in get1index
Here is a similar error message:
any.list[[0]]
## Error in any.list[[0]] :
## attempt to select less than one element in get1index <real>
END

Create spatial objects in R useful for coordinates() and spsample()

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.

Resources