ANTsX / ANTsR

R interface to the ANTs biomedical image processing library
https://antsx.github.io/ANTsR
Apache License 2.0
127 stars 35 forks source link

How to iterate an iMath function over many images #361

Closed ptsii closed 1 year ago

ptsii commented 2 years ago

I want to run a loop applying an iMath function ("MaurerDistance") to a bunch of images already in R. I tried:

for (i in ls(pattern="endo")) {
+ paste0(i,"_distanceMap")<-iMath(i,"MaurerDistance")
+ }

and got:

Error in antsImageRead(x, ...) : file does not exist

However, when I do iMath to an individual file, I don't get any error. What am I missing?

-Tom

ptsii commented 2 years ago

Figured it out:

for (i in ls(pattern=glob2rx("pattern_shared_by_R_objects_you_want_to_use*"))) {
VariableName<-i
outputVariableName<-paste0(i,"_disMap")
print(paste0("calculating distance map of ", VariableName))
assign( outputVariableName, iMath(eval(as.name(VariableName)),"MaurerDistance")
}

The first line finds all R objects that start with: "pattern_shared_by_R_objects_you_want_to_use" and submits them to the "for" loop The loop creates variables, prints a message indicating which file is being processed at each particular iteration, and the magic happens in the "assign" function. The "eval(as.name(VariableName))" ensures that the assign function treats the current value of "VariableName" as an R object.

Hope this helps someone!