Skip to content

Instantly share code, notes, and snippets.

@czarrar
Last active August 29, 2015 14:15
Show Gist options
  • Save czarrar/435befad24c06ae71bcf to your computer and use it in GitHub Desktop.
Save czarrar/435befad24c06ae71bcf to your computer and use it in GitHub Desktop.
Guide to loading brain imaging (nifti) data into R
# Installing the niftir package from github
# note: if you have a mac, this package has some open issues so I might recommend using another package (see below)
## Various Dependencies
cat("Installing various dependencies\n")
install.packages(
c("codetools", "foreach", "doMC", "multicore", "getopt", "optparse",
"bigmemory", "biganalytics", "bigmemory.sri")
, repos="http://cran.us.r-project.org")
install.packages(
c("plyr", "Rcpp", "RcppArmadillo", "inline", "devtools"),
dependencies=TRUE
, repos="http://cran.us.r-project.org")
## Install BigAlgebra (old version)
cat("\nInstalling bigalgebra\n")
devtools::install_github("bigalgebra", "czarrar")
## Installing niftir and friends
cat("\nInstalling connectir and friends\n")
devtools::install_github("bigextensions", "czarrar")
devtools::install_github("niftir", "czarrar")
# Rniftilib
# If you have a mac, then you can try Rniftilib instead
install.package("Rniftilib")
# Loading data
path_to_file <- "path_to_file.nii.gz"
hdr <- read.nifti.header(path_to_file) # this file is only needed when writing the output
img <- read.nifti.image(path_to_file) # should be a 3D or 4D array
# Loading 4D data (via bigmemory)
## will load the data as a 2D matrix (time-points x voxels)
dat <- read.big.nifti4d(path_to_4d_file) # a big matrix is returned along with other elements in a S4 class
# Loading a mask
## sometimes we have a brain image with just 1s and 0s containing voxels of interest = 1.
## you can use this mask, for instance, to select the voxels (columns) in your time-series data
mask <- read.mask(path_to_mask_file)
dat <- do.mask(dat, mask)
# or you could also use: dat <- deepcopy(dat, cols=mask)
# Writing data
path_to_outfile <- "path_to_outfile.nii.gz"
write.nifti(img, hdr, outfile=path_to_outfile)
## or if you masked the data, then you need to supply the mask as well
write.nifti(dat, mask, hdr, outfile=path_to_outfile)
## if the output file already exists, then you can pass the 'overwrite=T' option
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment