rarraysfor-loopnifti

Find and Replace number to NA in array R


I have some NifTi files of brain images where there are lots of zeros that I want to replace with NAs but I'm not sure how to do it. I read in the description of the is.na() function that: "the generic function is.na<- sets elements to NA" so I thought I could use that, but it didn't work. Here is specifically what I tried:

library(RNifti)

in.path <- "R_Things/Voxel/"
out.path <- "R_Things/Outputs/"

ids <- c('100','101','102','103','104')

for (i in ids) {

a <- readNifti(paste0(in.path, i, ".nii.gz"))

is.na(a) <- 0


writeNifti(image=a, file=paste0(out.path, i, "_with_NAs.nii.gz"))

}

Any thoughts on what I could do differently would be very helpful, thanks!


Solution

  • For anyone interested, here was my final code thanks to @Baroque

    library(RNifti)
    
    in.path <- "R_Things/Voxel/"
    out.path <- "R_Things/Outputs/"
    
    ids <- c('100','101','102','103','104')
    
    for (i in ids) {
    
    a <- readNifti(paste0(in.path, i, ".nii.gz"))
    
    a[a==0] <- NA
    
    writeNifti(image=a, file=paste0(out.path, i, "_with_NAs.nii.gz"))
    
    }