admin管理员组

文章数量:1391850

The R terra package does not seem to have an is.numeric() function that works on a terra raster?

I indicate a hacky alternative below that is VERY SLOW. Can someone provide a more elegant solution?


#set up data
  library(terra)
  x1 = x2 = x3 = x4 = rast( nrows=180, ncols=360, nlyrs=1, xmin=-180, xmax=180, ymin=-90, ymax=90)
  x1[] = 1.0          
  x2[] = F
  x3[] = "cat"
  x4[] = as.integer(1)

#create multiband raster  
  r4 = c(x1,x2,x3,x4)

#test for numeric - the second hacky approach works SLOWLY, but hacky 
# Are the contents of my raster spooling out into memory? 
  sapply(r4, is.numeric)
  sapply(r4, function(x)is.numeric(x[]))

#test for bool - terra function works
  sapply(r4, is.bool)

#test for factor - works
  sapply(r4, is.factor)

#test for integer - second approach (terra function) works
  sapply(r4, is.integer)
  sapply(r4, is.int)


The R terra package does not seem to have an is.numeric() function that works on a terra raster?

I indicate a hacky alternative below that is VERY SLOW. Can someone provide a more elegant solution?


#set up data
  library(terra)
  x1 = x2 = x3 = x4 = rast( nrows=180, ncols=360, nlyrs=1, xmin=-180, xmax=180, ymin=-90, ymax=90)
  x1[] = 1.0          
  x2[] = F
  x3[] = "cat"
  x4[] = as.integer(1)

#create multiband raster  
  r4 = c(x1,x2,x3,x4)

#test for numeric - the second hacky approach works SLOWLY, but hacky 
# Are the contents of my raster spooling out into memory? 
  sapply(r4, is.numeric)
  sapply(r4, function(x)is.numeric(x[]))

#test for bool - terra function works
  sapply(r4, is.bool)

#test for factor - works
  sapply(r4, is.factor)

#test for integer - second approach (terra function) works
  sapply(r4, is.integer)
  sapply(r4, is.int)


Share Improve this question edited Mar 12 at 15:57 Robert Hijmans 48.2k4 gold badges62 silver badges73 bronze badges asked Mar 12 at 4:57 Jacob StrunkJacob Strunk 211 silver badge2 bronze badges 1
  • Consider, your careful 'what type?' above provoked a change in code base where your question is documented. If you are working with raster data often, become comfortable with frequently git clone(ing) the repository, and R CMD build terra, R CMD INSTALL (name of .gz built) as terra under ongoing development and responsive to reasonable suggestions such as yours. Just moved from 1.8.23 to 1.8.34 based on this. – Chris Commented Mar 13 at 16:47
Add a comment  | 

1 Answer 1

Reset to default 4

You can do

sapply(r4[1], is.numeric)
#lyr.1 lyr.1 lyr.1 lyr.1 
# TRUE FALSE FALSE  TRUE 

And with terra 1.8.34 you can do:

is.num(r4)
#[1]  TRUE FALSE FALSE  TRUE

本文标签: What is the correct terra usage to achieve isnumeric on an R terra package rasterStack Overflow