ANTsR icon indicating copy to clipboard operation
ANTsR copied to clipboard

How to iterate an iMath function over many images

Open ptsii opened this issue 2 years ago • 1 comments

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 avatar Mar 05 '22 17:03 ptsii

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!

ptsii avatar Mar 14 '22 03:03 ptsii