Learn R Programming

ciftiTools

CIFTI files contain brain imaging data in “grayordinates,” which represent the gray matter as cortical surface vertices (left and right) and subcortical voxels (cerebellum, basal ganglia, and other deep gray matter). ciftiTools provides a unified environment for reading, writing, visualizing and manipulating CIFTI-format data. It supports the “dscalar,” “dlabel,” and “dtseries” intents. Grayordinate data is read in as a "xifti" object, which is structured for convenient access to the data and metadata, and includes support for surface geometry files to enable spatially-dependent functionality such as static or interactive visualizations and smoothing.

Citation

If you use ciftiTools, please cite our paper:

Pham, D. D., Muschelli, J., & Mejia, A. F. (2022). ciftiTools: A package for reading, writing, visualizing, and manipulating CIFTI files in R. NeuroImage, 250, 118877.

You can also obtain citation information from within R like so:

citation("ciftiTools")

Installation

You can install ciftiTools from CRAN with:

install.packages("ciftiTools")

Additionally, most of the ciftiTools functions require the Connectome Workbench, which can be installed from the HCP website.

Quick start guide

# Load the package and point to the Connectome Workbench --------
library(ciftiTools)
ciftiTools.setOption("wb_path", "path/to/workbench")

# Read and visualize a CIFTI file -------------------------------
cifti_fname <- ciftiTools::ciftiTools.files()$cifti["dtseries"]
surfL_fname <- ciftiTools.files()$surf["left"]
surfR_fname <- ciftiTools.files()$surf["right"]

xii <- read_cifti(
  cifti_fname, 
  surfL_fname=surfL_fname, surfR_fname=surfR_fname,
  resamp_res=4000
)

view_xifti_surface(xii) # or plot(xii)
# view_xifti_volume(xii) if subcortex is present

# Access CIFTI data ---------------------------------------------
cortexL <- xii$data$cortex_left
cortexL_mwall <- xii$meta$medial_wall_mask$left
cortexR <- xii$data$cortex_right
cortexR_mwall <- xii$meta$medial_wall_mask$right
# subcortVol <- xii$data$subcort
# subcortLabs <- xii$meta$subcort$labels
# subcortMask <- xii$meta$subcort$mask
surfL <- xii$surf$cortex_left
surfR <- xii$surf$cortex_right

# Create a `"xifti"` from data ----------------------------------
xii2 <- as.xifti(
  cortexL=cortexL, cortexL_mwall=cortexL_mwall,
  cortexR=cortexR, cortexR_mwall=cortexR_mwall,
  #subcortVol=subcortVol, subcortLabs=subcortLabs,
  #subcortMask=subcortMask,
  surfL=surfL, surfR=surfR
)

# Write a CIFTI file --------------------------------------------
write_cifti(xii2, "my_cifti.dtseries.nii")

Vignette/Demo

See this link to view the tutorial vignette.

List of commonly-used functions

Basics: reading, plotting, writing

  • ciftiTools.setOption: Necessary to point to the Connectome Workbench each time ciftiTools is loaded.
  • read_cifti: Read in a CIFTI file as a "xifti" object.
  • view_xifti Plot the cortex and/or subcortex. Has many options for controlling the visualization.
  • write_cifti: Write a "xifti" object to a CIFTI file.

Manipulating CIFTI files

  • resample_cifti: Resample to a different resolution.
  • separate_cifti: Separate a CIFTI file into GIFTI and NIFTI files.
  • smooth_cifti: Smooth the data along the surface.
  • (Use run_wb_cmd to execute Connectome Workbench commands from R)

Manipulating "xifti" objects

  • apply_xifti: Similar to base::apply.
  • combine_xifti: Combine "xifti"s with non-overlapping brain structures.
  • convert_xifti: Convert between dlabel, dscalar, and dtseries.
  • impute_xifti: Impute data values from neighboring vertices/voxels.
  • merge_xifti: Concatenate "xifti"s.
  • move_from_mwall: Convert the medial wall mask to a data value, deleting the mask.
  • move_to_mwall: Mask out a particular data value.
  • newdata_xifti: Replace the data values.
  • resample_xifti: Resample to a different resolution.
  • scale_xifti: Similar to base::scale.
  • select_xifti: Rearrange the columns to reorder, take a subset, or repeat them.
  • smooth_xifti: Smooth the data along the surface.
  • transform_xifti: Apply a vectorizable function.

Surface geometry

  • load_surf: Load a surface geometry included in the package.
  • read_surf: Read in a GIFTI surface geometry file as a "surf" object.
  • write_surf: Write a "surf" object to a GIFTI surface geometry file.

Parcellations

  • apply_parc: Apply a function to each parcel separately.
  • load_parc: Load a parcellation included in the package.

See NAMESPACE for a full list of all exported functions.

Illustrations

FAQ

Why is a CIFTI file that has been read in called a "xifti"?

The "xifti" object is a general interface for not only CIFTI files, but also GIFTI and NIFTI files. For example, we can plot a surface GIFTI:

gii_surf <- read_surf(ciftiTools.files()$surf["left"])
xii <- as.xifti(surfL=gii_surf)
plot(xii)

We can also convert metric GIFTI files and/or NIFTI files to CIFTI files (or vice versa) using the "xifti" object as an intermediary.

How do I convert to CIFTI Format…

…from NIFTI volumetric cortical data?

The cortex data will have to be projected to the surface. If the data are in BIDS format, then fMRIprep can be used to convert the volumetric cortex data to fsaverage surface space. Note that ciftiTools::remap_cifti can be used after to convert from fsaverage to fs_LR surface space, since some CIFTI-related packages assume the data are registered to fs_LR. fMRIprep is a wrapper around FreeSurfer commands; alternatively, commands from FreeSurfer can be used directly. Relevant commands include mri_vol2surf, fslregister, mris_preproc, and mris_convert. The result of mris_convert will be in GIFTI format, which can be converted into CIFTI format with ciftiTools::as.cifti.

More options include those from the Connectome Workbench, ciftify, DeepPrep, and Nilearn. We also welcome input from the community about additional ways for converting from volumetric data to CIFTI format.

…from NIFTI volumetric subcortical data?

Use the Connectome Workbench command -cifti-create-dense-from-template.

How do I visualize cortical data without applying shading to the mesh geometry?

The 3D shading may make certain plots more difficult to interpret, if the color scale varies from dark to light: darker regions might be in a shadow, or their values might be lower. To skip shading, use the argument material=list(lit=FALSE) to view_xifti_surface.

How do I get VoxelIndicesIJK or the MNI coordinates for the subcortex?

For a "xifti" object xii with subcortical data, the mask of data locations is saved in xii$meta$subcort$mask. To obtain the array coordinates of the in-mask locations, use which(xii$meta$subcort$mask, arr.ind=TRUE) - 1. This matrix has each subcortical voxel along the rows, and its I, J, and K array coordinates along the three columns. 1 is subtracted because the coordinates should begin with 0 rather than 1. It’s equivalent to the original CIFTI metadata entry VoxelIndicesIJK. To convert array coordinates to MNI coordinates, multiply by the transformation matrix xii$meta$subcort$trans_mat:

VoxIJK <- which(xii$meta$subcort$mask, arr.ind=TRUE) - 1
VoxIJK <- cbind(VoxIJK, 1) # for 4th col of transform mat (translation)
VoxXYZ <- t(xii$meta$subcort$trans_mat[seq(3),] %*% t(VoxIJK)) # MNI coords

Why do the labels/orders of Limbic A and Limbic B in the Yeo 17 parcellation appear swapped, relative to this Figure from an earlier paper?

The copy of the Yeo 17 parcellation included in ciftiTools is correct. An earlier figure for the Yeo 17 parcellation had mistakenly swapped these labels, but this error has since been corrected. See the “Important note” from this page: https://github.com/ThomasYeoLab/CBIG/blob/master/stable_projects/brain_parcellation/Schaefer2018_LocalGlobal/README.md#version-12-schaefer2018_roisparcels_717networks_order

Related R extensions

  • NIFTI files: oro.nifti, RNifti
  • GIFTI files: gifti
  • CIFTI files: cifti can read in any CIFTI file, whereas ciftiTools provides a user-friendly interface for CIFTI files with the dscalar, dlabel, and dtseries intents only.
  • Other structural neuroimaging files: fsbrain
  • xml files: xml2
  • Interactive 3D rendering: rgl

Surface rendering issue on Mac OS Tahoe

On Mac OS Tahoe, Open GL windows will not work due to a problem with rgl and XQuartz (https://github.com/dmurdoch/rgl/issues/488#issuecomment-3506547361). To render the cortical surface with plot or view_xifti_surface, you will need to choose to use the htmlwidget instead of the Open GL window. Set widget=TRUE for interactive viewing, and set fname="*.html" to write files. The ciftiTools development team is currently exploring workarounds for this issue.

Data acknowledgement

The following data are included in the package for convenience:

Example CIFTI files provided by NITRC.

Cortical surfaces provided by the HCP, according to the Data Use Terms:

Data were provided [in part] by the Human Connectome Project, WU-Minn Consortium (Principal Investigators: David Van Essen and Kamil Ugurbil; 1U54MH091657) funded by the 16 NIH Institutes and Centers that support the NIH Blueprint for Neuroscience Research; and by the McDonnell Center for Systems Neuroscience at Washington University.

Several parcellations provided by Thomas Yeo’s Computational Brain Imaging Group (CBIG):

  1. Yeo, B. T. T. et al. The organization of the human cerebral cortex estimated by intrinsic functional connectivity. J Neurophysiol 106, 1125–1165 (2011).
  2. Schaefer, A. et al. Local-Global Parcellation of the Human Cerebral Cortex from Intrinsic Functional Connectivity MRI. Cereb Cortex 28, 3095–3114 (2018).
  3. Kong, R. et al. Individual-Specific Areal-Level Parcellations Improve Functional Connectivity Prediction of Behavior. Cerebral Cortex (2021).

Copy Link

Version

Install

install.packages('ciftiTools')

Monthly Downloads

539

Version

0.21.1

License

GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Amanda Mejia

Last Published

September 9th, 2026

Functions in ciftiTools (0.21.1)

as.xifti

Assemble a "xifti" from data
as.matrix.xifti

Convert a "xifti" to a matrix
apply_xifti

Apply a function along the rows or columns of a "xifti"
area_original_Param

area_original_Param
ciftiTools.listOptions

List ciftiTools options
ciftiTools.getOption

Get a ciftiTools option
ciftiTools.files

ciftiTools files
ciftiTools

ciftiTools: Tools for Reading and Visualizing CIFTI Brain Files
ciftiTools_msg

Print suppressible message
check_cifti_type

Check CIFTI type
ciftiTools_warn

Print suppressible warning
brainstructures_Param_existing

brainstructures
as.metric_gifti

Format metric data as a "gifti"
ciftiTools.checkOption

Validate a ciftiTools option and value
ciftiTools.setOption

Set a ciftiTools option
as.surf_gifti

Format surface data as a "gifti"
combine_xifti

Combine "xifti"s with non-overlapping brain structures
dim.xifti

Dimensions of a "xifti"
cifti_fname_Param

cifti_fname
cifti_component_suffix

Get CIFTI component suffix default
coordlist_to_vol

Convert coordinate list to volume
dist_from_mask_surf

Distance from mask on surface
crop_image

Crop image
crop_vol

Crop a 3D array
check_render_backend

Verify the rgl rendering backend has what it needs. Required deps depend on the path that will run: native -> rgl HTML widget fallback -> rgl + htmlwidgets web PNG (Tahoe etc) -> rgl + webshot2 + htmlwidgets + Chrome
convert_xifti

Convert "xifti"
edit_mask_surf

Edit mask on surface
expand_color_pal

Interpolates between entries in the input palette to make a larger palette with COLOR_RES entries.
fix_gifti_mwall

Fix GIFTI medial wall
confirm_wb_cmd_path

Confirm the Connectome Workbench command path
expect_equal_xifti

Expect these "xifti"s to match
even_vert_samp

Evenly sample vertices of mesh
fix_xifti

Fix a "xifti"
infer_resolution

Infer resolution from "xifti" and surfaces
impute_xifti

Impute "xifti" data
get_wb_cmd_path

Get the Connectome Workbench command path
get_kwargs

Get kwargs
get_misc_meta_from_cifti_xml

Extract misc metadata from CIFTI
format_path

Format a path
faces_Param

faces
get_cifti_extn

Get CIFTI file extension
get_intn_meta_from_cifti_xml

Extract intent-specific metadata from CIFTI
.onAttach

Message on attach
get_data_meta_from_cifti_xml

Extract data-related metadata from CIFTI
flatten_xifti

Flatten a "xifti"
header_cifti

Get NIFTI header (of a CIFTI)
info_cifti

Get CIFTI metadata
is.surf

Validate a "surf" object (vertices + faces)
is.cifti

Validate a "xifti" object
is.xifti

Validate a "xifti" object.
is.xifti_data

Validate the "data" component of a "xifti" object
idx_Param

idx
is.xifti_meta

Validate the "meta" component of a "xifti" object
is.fname

Is this an existing file path?
is.nummat

Validate a numeric matrix
is.subcort_labs

Validate a factor vector of subcortical labels
is.3D_mask

Validate a 3d binary mask
load_parc

Load a parcellation included in ciftiTools
make_trans_mat

Make the subcortical transformation matrix
make_subcort

Make the subcortical components of a "xifti"
load_surf

Load a "surf" included in ciftiTools
make_color_pal

Make a color palette.
load_sub_parc

Load subcortical parcellation
is_tahoe

Is the host running macOS Tahoe (26.0+)?
make_cortex

Make the cortical components of a "xifti"
labels_Description

labels
move_from_submask

Move data locations from subcortex mask
move_to_mwall

Move data locations to the medial wall
match_input

Match user inputs to expected values
merge_kwargs

Merges two kwargs
make_xifti

Assemble a "xifti" object
merge_xifti

Concatenate "xifti"s
move_from_mwall

Move data locations from medial wall
parc_add_subcortex

Add subcortex to cortical parcellation
original_fnames_Param_remapped

original_fnames: for remapping
parc_mean_mat

Make parcellation mean matrix
pad_vol

Pad a 3D Array
mask_with_boundary_surf

Apply Mask With Boundary To Mesh
newdata_xifti

Replace the data in a "xifti"
original_fnames_Param_resampled

original_fnames: for resampling
move_to_submask

Move data locations to the subcortex mask
ncol_xifti

Counts the number of columns in a "xifti".
parc_borders

Parcellation borders
match_exactly

Do these character vectors match exactly?
plot.surf

S3 method: plot surface
plot.xifti

S3 method: use view_xifti to plot a "xifti" object
mask_surf

Mask surface
parc_vals_to_xifti

Convert parcellation values to "xifti"
qform_from_Tfmat

Derive qform metadata in NIFTI header from transformation matrix
read_cifti

Read a CIFTI file
nrow_xifti

Counts the number of rows (vertices + voxels) in a "xifti".
mask_Param_vertices

mask: vertices
read_cifti_convert

Read a CIFTI file quickly
platform

Platform detection and per-platform overrides
radial_order_surf

Order Vertices on Circular Manifold
read_cifti_flat

Read only the data matrix in a CIFTI file
read_cifti_separate

Read a CIFTI file with optional resampling
remap_cifti

Remap CIFTI data
read_xifti2

Read in GIFTI files as a "xifti" object
remove_xifti

Remove a component from a "xifti"
read_dir_Param_separated

read_dir: separated files
replace_NA_with_label

Replace NA values in dlabel "xifti" with a new label.
resamp_res_Param_optional

resamp_res: optional
resamp_method_Param

resamp_method
remap_cifti_wrapper

remap_cifti wrapper
remap_gifti

Remap GIFTI metric or label data
read_surf

Get a "surf" object
resamp_res_Param_required

resamp_res: required
rgl_interactive_plots_Description

Navigating and Embedding the Interactive Plots
resample_cifti

Resample CIFTI data
resample_gifti

Resample a GIFTI file (with its ROI)
resample_cifti_from_template

Resample a CIFTI from a template
resample_surf

Resample a "surf" object
resample_cifti_components

Resample a series of GIFTIs related to a CIFTI file
resample_cifti_wrapper

resample_cifti wrapper
rgl_static_plots_Description

Embedding the Static Plots
resample_cifti_default_fname

Get resampled file name default
separate_cifti

Separate a CIFTI file
run_wb_cmd

Wrapper for Connectome Workbench Commands
rotate_surf

Rotate a "surf" object
select_xifti

Select columns of a "xifti"
smooth_cifti

Smooth CIFTI data
smooth_gifti

Smooth a metric GIFTI file
separate_cifti_wrapper

separate_cifti wrapper
set_names_xifti

Set "xifti" column names
scale_xifti

Scale CIFTI
separate_cifti_files

Separate CIFTI: file names
surfL_Param_optional

surfL
surfR_Param_optional

surfR
surfR_fname_Param

surfR_fname
supported_intents

The NIFTI intents supported by ciftiTools
summary.xifti

Summarize a "xifti" object
summary.surf

Summarize a "surf" object
substructure_table

Substructure table
surfL_fname_Param

surfL_fname
surfL_original_fname_Param

surfL_original_fname
surfL_target_fname_Param

surfL_target_fname
surf_area

Surface area calculation
unmask_subcortex

Undo the volumetric mask to the subcortex
surface_plot_Params

Surface plot
surfR_original_fname_Param

surfR_original_fname
template_xifti

Make a template "xifti" object
sys_path

unvec_vol

Convert vectorized data back to volume
transform_xifti

Apply a univariate transformation to a "xifti" or pair of "xifti"s.
unmask_cortex

Unmask cortex
surfR_target_fname_Param

surfR_target_fname
vertices_Param

vertices
use_color_pal

Use a color palette
view_xifti

View a "xifti" object
view_comp

View composite of images
view_surf

View "surf" object(s)
view_xifti.cbar

Make the colorbar for view_xifti_surface
verbose_Param_TRUE

verbose: TRUE
verbose_Param_FALSE

verbose: FALSE
vert_adjacency

Vertex Adjacency Matrix
view_xifti.cleg

Draw color legend for qualitative mode
vox_locations

Get spatial locations of each voxel
view_xifti_surface.color

Get the palettes and data color mapping for view_xifti_surface
wb_path_request

Request "wb_path"
view_xifti_surface.mesh_val

Get the mesh(es) and data values for view_xifti_surface
view_xifti_surface

View cortical surface data in a "xifti"
view_xifti.title

Get title for view_xifti_surface or view_xifti_volume
view_xifti_surface.surf_hemi

Sort out surface & hemisphere args for view_xifti_surface
view_xifti_volume

View subcortical data in a "xifti"
view_xifti_surface.draw_mesh

Draw brain hemisphere mesh in RGL
view_xifti_surface.draw_title

Draw title in RGL
write_subcort_nifti

Write subcortical data to NIFTI files
write_cifti_from_separate

Write a CIFTI file from NIFTI and GIFTI files
welcome_msg

Welcome message
write_label_table

Write label table to text file
write_metric_gifti

Write a data matrix to a GIFTI metric file
write_surf_gifti

Write a "surf" to a GIFTI surface file
write_xifti2

Write a "xifti" object to GIFTI and NIFTI files
write_cifti

Write a CIFTI file from a "xifti" object
write_dir_Param_generic

write_dir: generic
x_Param_xifti

x: xifti
write_spheres

Generate GIFTI sphere surface files
xifti_Param

xifti
xml_cifti

Get XML of a CIFTI
all_integers

All integers?
S3_Ops

"xifti" S3 Ops methods
ROY_BIG_BL

"ROY_BIG_BL" color palette
apply_parc

Apply function over locations in each parcel
S3_Summary

"xifti" S3 Summary methods
ROI_brainstructures_Param_all

ROI_brainstructures
add_surf

Add HCP surface(s) to a "xifti"
S3_Math

"xifti" S3 Math methods
Tfmat_from_qform

Derive transformation matrix from qform metadata in NIFTI header
apply_platform_overrides

Run every override whose when matches the host. Errors inside apply become warnings so a bad override can't block attach.
boundary_mask_surf

Boundary region of a mask
assure_parc

Assure this is a parcellation
area_target_Param

area_target_Param