1

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!

beanboy
  • 217
  • 1
  • 9

2 Answers2

0

Here are some possible option to replace 0 by NA

> replace(a, a == 0, NA)
[1] NA  1  2 NA  3 -1

> a * NA^(a == 0)
[1] NA  1  2 NA  3 -1

Dummy Data

> a <- c(0, 1, 2, 0, 3, -1)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • The `a * NA^(a == 0)` is charming just for seeing a truth eval in an exponent. – Chris Jun 09 '21 at 01:31
  • Thanks @ThomasIsCoding but believe it or not neither of those worked. I guess it might have to do with the fact that the data is in an array? – beanboy Jun 09 '21 at 16:32
0

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"))

}
beanboy
  • 217
  • 1
  • 9