Using R with AFNI

AFNI already has a host of programs that use R to analyze MRI data – 3dLME, 3dMVM, 3dMEMA, etc.  Suppose you wanted to create your own functions that use R to manipulate data – well here’s a quick introduction.  In this quick example, here is how to “Auto Mask” your dataset in R.

source('path/to/AFNI/AFNIio.R')
thedata = read.AFNI('run1+orig')
names(thedata)

#get value at voxel at time point
#here midpoint x, y, z, time point 66
thedata$brk[32,32,10,66]
testdata = thedata$brk[,,,1]
for ( i in 1:dim(testdata)[1] ) {
   for ( j in 1:dim(testdata)[2] ) {
      for ( k in 1:dim(testdata)[3] ) {
         if( testdata[i,j,k] > 400 ) {testdata[i,j,k] = 1;}
         else {testdata[i,j,k] = 0;}
       }
    }
}
write.AFNI("test_mask+orig", brk=testdata, label=NULL, note="Masked", orient=thedata$orient, view='+orig', defhead=thedata$header)

I take some shortcuts by just making the output dataset header identical to the input dataset.  But you get the general sense for how easy it is to open an AFNI dataset in R, manipulate the data and write it back out.

Comments are closed.