-
Notifications
You must be signed in to change notification settings - Fork 0
/
fMRI_matrix_extraction_script.R
64 lines (49 loc) · 2.84 KB
/
fMRI_matrix_extraction_script.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
##############################################################################
########### This is the script for extracting within and between connectivity
##############################################################################
#Project: Long-term effects of prenatal infection on the human brain: a prospective multimodal neuroimaging study (in the Generation R cohort).
################ read the data #########################
# read the brain label data
setwd("PUT_PATH_WHERE_YOU_KEEP_THE_DATA")
gordon <- read.table("Gordon333_FreesurferSubcortical.32k_fs_LR.dlabel.CLUT.txt", sep = "\t")
labels <- gordon[-seq(2, 704, 2), ]
length(labels)
# clean the label names
labels <- gsub('^[LR]_', "", labels)
labels_group <- gsub("\\_.*", "",labels)
# the unique label names
labels_unique <- unique(labels_group)
################ map the data with brain ################
# the ids
id <- readRDS("sub-id_has_conMat.rds")
############ extract within and between connectivity
wit_bet_Con <- lapply(id, function(i) {
################ read the raw data
path <- paste0("path_to_the_data") # path to the data
conMat <- read.table(path)
################ map the brain data with the labels ################
conmat <- as.matrix(conMat)
# we need to set diagonal to NA in order to calculate the mean of within and between connectivity
diag(conmat) <- NA
colnames(conmat) <- labels_group
rownames(conmat) <- labels_group
################ calculate the mean within and between connectivity ################
# go through all the possible combinations of parcels to calculate the mean connectivity between each parcel
between <- lapply(1:(length(labels_unique)-1), function(col){ # go through the parcels
bet_mean <- sapply((col+1):length(labels_unique), function(row){
mean(conmat[rownames(conmat) == labels_unique[row],
colnames(conmat) == labels_unique[col]])
})
})
# create an empty matrix to fill in within and between connectivity
Mat <- matrix(NA,length(labels_unique),length(labels_unique))
Mat[lower.tri(Mat, diag=F)] <- unlist(between)
Mat[upper.tri(Mat, diag=F)] <- t(Mat)[upper.tri(Mat, diag=F)]
# go through all the parcels to calculate the mean connectivity within each parcel
con_within <- sapply(labels_unique, function(x) {mean(conmat[rownames(conmat) == x, colnames(conmat) == x], na.rm=TRUE)})
diag(Mat) <- con_within
colnames(Mat) <- labels_unique
rownames(Mat) <- labels_unique
return(Mat)
})
saveRDS(wit_bet_Con, "within_between_fullCon_genr.rds")