Last updated: 2021-01-15

Checks: 7 0

Knit directory: Pragmatic-language-dataset-code/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20210114) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 8beecca. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Untracked files:
    Untracked:  code/aparcs_ml.R
    Untracked:  code/aparcs_ml_regression.R
    Untracked:  data/145_FS.png
    Untracked:  data/Civet_aparc_lh_thickness.csv
    Untracked:  data/Civet_aparc_rh_thickness.csv
    Untracked:  data/FS_aparc_lh_thickness.csv
    Untracked:  data/FS_aparc_rh_thickness.csv
    Untracked:  data/ROI_catROIs_aparc_DK40_thickness.csv
    Untracked:  data/data_fluidez_sst_edim2.csv

Unstaged changes:
    Modified:   analysis/_site.yml
    Modified:   analysis/about.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Workflow.Rmd) and HTML (docs/Workflow.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 8beecca JalilRT 2021-01-15 Publish the initial files for ToM-and-its-elusive-structural-substrate-code
html 57fe138 JalilRT 2021-01-15 Build site.
Rmd d4f3c5d JalilRT 2021-01-15 Publish the initial files for ToM-and-its-elusive-structural-substrate-code

Preprocessing

Cortical thickness as a Psychometric predictor

Load the packages

pacman::p_load(tidyverse,dplyr,
               caret, pROC,
               readxl, cowplot,
               caTools,
               class)

Calculating k-nn neighboors regression

## CAT12 ##
lr.cat=read.csv("data/ROI_catROIs_aparc_DK40_thickness.csv")
lr.cat.r<-lr.cat %>% select(starts_with('r'))
not_all_na <- function(x) any(!is.na(x))
lr.cat.r<-lr.cat.r %>% select_if(not_all_na)
lr.cat<-lr.cat %>% mutate(rMeanThickness=rowMeans(lr.cat.r))
lr.cat<-data.frame(lr.cat[-139,],software=rep("1",145))
lr.cat$names<-str_replace(lr.cat$names,"_T1w","")
lr.cat<-lr.cat %>% mutate(MeanThickness=lr.cat %>% select(rMeanThickness,lMeanThickness) %>% rowMeans())

## FS ##
lh.fs=read.csv("data/FS_aparc_lh_thickness.csv",sep = "\t",stringsAsFactors = T)
rh.fs=read.csv("data/FS_aparc_rh_thickness.csv",sep = "\t",stringsAsFactors = T)
lr.fs=cbind(lh.fs,rh.fs)
lr.fs=select(lr.fs,-c("BrainSegVolNotVent","eTIV","rh.aparc.thickness"))
lr.fs=lr.fs %>% mutate(Order = as.numeric(gsub("sub-", "", lh.aparc.thickness))) %>% arrange(Order)
lr.fs=data.frame(lr.fs[-139,],software=rep("0",145))
col.lr.fs=str_replace(colnames(lr.fs),"_thickness","")
colnames(lr.fs)=col.lr.fs
col.lr.fs=str_replace(colnames(lr.fs),"h_","")
colnames(lr.fs)=col.lr.fs
lr.fs<-lr.fs %>% mutate(MeanThickness=lr.fs %>% select(rMeanThickness,lMeanThickness) %>% rowMeans())

## CIVET ##
lr.civet.l=read.csv("data/Civet_aparc_lh_thickness.csv")
lr.civet.r=read.csv("data/Civet_aparc_rh_thickness.csv")
lr.civet=cbind(lr.civet.l,lr.civet.r)
lr.civet=lr.civet[-34]
lr.civet=data.frame(lr.civet,software=rep("2",145))
lr.civet<-lr.civet %>% mutate(MeanThickness=lr.civet %>% select(rMeanThickness,lMeanThickness) %>% rowMeans())


#### Merge Software values #### only 31 structures per hemisphere

l.cfsci<-list(lr.fs,lr.cat,lr.civet)
fscc.lr <- Reduce(function(...) merge(..., all=TRUE), l.cfsci)
lr.fs.cat.civet<-fscc.lr %>% select_if(~!any(is.na(.)) > 0)

### Convert to factors ###
lr.fs.cat.civet$software <- factor(lr.fs.cat.civet$software, 
                         levels = c(1, 0, 2), 
                         labels = c("cat", "fs","civet"))   

### Select a samples ###
set.seed(42)
######## k-Nearest neighbors (kNN) ########

######## Classification of laterality for FreeSurfer ########
lr.fs<-lr.fs.cat.civet %>% filter(software == "fs")
psych.data<-read.csv("data/data_fluidez_sst_edim2.csv")
lr.fs.psych<-data.frame(cbind(lr.fs[-81,-65],psych.data[-c(139,81),-1])) #remove left side participant = 81
lr.fs.psych<-na.omit(lr.fs.psych)

# Training classification
lr.fs.psych$Hemis<-factor(lr.fs.psych$Hemis)
fs.train.c <- createDataPartition(y = lr.fs.psych$Hemis, p = 0.7, list = FALSE) #training with proportion (p) 
fs.train <- lr.fs.psych[fs.train.c,]  
fs.test <- lr.fs.psych[-fs.train.c,]

## parameters ##
#control with more
sof.control <- trainControl(
  method = "repeatedcv", 
  number = 10, repeats = 3,
  summaryFunction = twoClassSummary,
  classProbs = TRUE,
  verboseIter = TRUE,
  savePredictions = "final")

#preprocessing with center (mean) and scale (sd), this is for normalizing
fs.knntrain <- train(Hemis ~ ., 
                         data = fs.train, 
                         method = "knn",  
                         metric="ROC",
                         tuneLength = 20,
                         trControl = sof.control,
                         preProc = c("center","scale"),
                         tuneGrid = expand.grid(k = 1:60))
class(fs.knntrain)
fs.knntrain
plot(fs.knntrain) #accuracy plot with different k

Version Author Date
57fe138 JalilRT 2021-01-15
varImp(fs.knntrain)

## Predict ##
fs.knnPrediccion <- predict(fs.knntrain, newdata = fs.test )
confusionMatrix(fs.knnPrediccion, fs.test$Hemis) #accuracy of model and others

## REGRESSION

reg.control <- trainControl(
  method = "repeatedcv", 
  number = 10, repeats = 3,
  verboseIter = TRUE,
  savePredictions = "final")

reg.fs.knntrain<-train(Edimburgo ~ .,
                          data = fs.train %>% select(-c("Hemis","Fluidez","SSTcomp","MeanThickness","rMeanThickness","lMeanThickness")),
                          tuneGrid = expand.grid(k=1:70),
                          method = 'knn',
                          metric = 'Rsquared',
                          trControl = reg.control,
                          preProc = c('center', 'scale'))

reg.fs.psych.predictions <- reg.fs.knntrain %>% predict(fs.test %>% select(-c("Hemis","Fluidez","SSTcomp")))

# Fluidez 

freg.fs.knntrain<-train(Fluidez ~ .,
                       data = fs.train %>% select(-c("Hemis","Edimburgo","SSTcomp","MeanThickness","rMeanThickness","lMeanThickness")),
                       tuneGrid = expand.grid(k=1:70),
                       method = 'knn',
                       metric = 'Rsquared',
                       trControl = reg.control,
                       preProc = c('center', 'scale'))

freg.fs.psych.predictions <- freg.fs.knntrain %>% predict(fs.test%>% select(-c("Hemis","Edimburgo","SSTcomp","MeanThickness","rMeanThickness","lMeanThickness")))

# SSTcomp

sreg.fs.knntrain<-train(SSTcomp ~ .,
                       data = fs.train%>% select(-c("Hemis","Edimburgo","Fluidez","MeanThickness","rMeanThickness","lMeanThickness")),
                       tuneGrid = expand.grid(k=1:70),
                       method = 'knn',
                       metric = 'Rsquared',
                       trControl = reg.control,
                       preProc = c('center', 'scale'))

sreg.fs.psych.predictions <- sreg.fs.knntrain %>% predict(fs.test%>% select(-c("Hemis","Edimburgo","Fluidez","MeanThickness","rMeanThickness","lMeanThickness")))

### Comparison metrics

# Edimburgo 
varImp(reg.fs.knntrain)
fs.mean.pred<-tibble(MeanThickness=fs.test$MeanThickness,Predictions=reg.fs.psych.predictions,Observed=fs.test$Edimburgo)
fs.mean.pred<-fs.mean.pred %>% gather("Group","Edinburgh",2:3)
ggthemr::ggthemr("fresh")
fs_edim<-ggplot(fs.mean.pred,aes(x=Edinburgh,y=MeanThickness, colour=Group))+geom_point()+
  ylab("Mean Thickness (mm)")+
  geom_smooth(method = "lm", formula = y~x, se = F) + theme(legend.position = c(.2, .9),
                                                            legend.title = element_blank())

# Fluidez
varImp(freg.fs.knntrain)
fs.mean.pred.Fluidez<-tibble(MeanThickness=fs.test$MeanThickness,Predictions=freg.fs.psych.predictions,Observed=fs.test$Fluidez)
fs.mean.pred.Fluidez<-fs.mean.pred.Fluidez %>% gather("Group","Fluency",2:3)
fs_flu<-ggplot(fs.mean.pred.Fluidez,aes(x=Fluency,y=MeanThickness, colour=Group))+geom_point()+
  ylab("")+
  geom_smooth(method = "lm", formula = y~x, se = F)+ theme(legend.position = c(.85, .9),
                                                           legend.title = element_blank())

# SSTcom
asdf<-varImp(sreg.fs.knntrain)
plot(asdf,top=4)

Version Author Date
57fe138 JalilRT 2021-01-15
fs.mean.pred.SSTcom<-tibble(MeanThickness=fs.test$MeanThickness,Predictions=round(sreg.fs.psych.predictions),Observed=fs.test$SSTcom)
fs.mean.pred.SSTcom<-fs.mean.pred.SSTcom %>% gather("Group","Comprehension",2:3)
fs_sst<-ggplot(fs.mean.pred.SSTcom,aes(x=Comprehension,y=MeanThickness, colour=Group))+geom_point()+
  ylab("")+
  geom_smooth(method = "lm", formula = y~x, se = F)+ theme(legend.position = c(.2, .9),
                                                           legend.title = element_blank())

##### Plot figure #####
FS_145<-ggdraw()+draw_image("/home/jalil/Documents/Doctorado/Pragmaticlab/paper_dataR/Project/145_FS.png")
fig1<-plot_grid(FS_145,fs_flu,fs_edim,fs_sst, labels = "AUTO")

Plots

FS_145

Version Author Date
57fe138 JalilRT 2021-01-15
fig1

Version Author Date
57fe138 JalilRT 2021-01-15

sessionInfo()
R version 3.6.3 (2020-02-29)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.1 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=es_MX.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=es_MX.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=es_MX.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=es_MX.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] class_7.3-15    caTools_1.18.0  cowplot_1.1.0   readxl_1.3.1   
 [5] pROC_1.16.2     caret_6.0-86    lattice_0.20-38 forcats_0.5.0  
 [9] stringr_1.4.0   dplyr_1.0.2     purrr_0.3.4     readr_1.4.0    
[13] tidyr_1.1.2     tibble_3.0.4    ggplot2_3.3.2   tidyverse_1.3.0
[17] workflowr_1.6.2

loaded via a namespace (and not attached):
 [1] nlme_3.1-151         bitops_1.0-6         fs_1.5.0            
 [4] lubridate_1.7.9      httr_1.4.2           rprojroot_1.3-2     
 [7] tools_3.6.3          backports_1.1.10     R6_2.5.0            
[10] rpart_4.1-15         mgcv_1.8-31          DBI_1.1.0           
[13] colorspace_1.4-1     nnet_7.3-12          withr_2.3.0         
[16] tidyselect_1.1.0     compiler_3.6.3       git2r_0.27.1        
[19] cli_2.1.0            rvest_0.3.6          pacman_0.5.1        
[22] ggthemr_1.1.0        xml2_1.3.2           labeling_0.4.2      
[25] scales_1.1.1         digest_0.6.27        rmarkdown_2.5       
[28] pkgconfig_2.0.3      htmltools_0.5.0      dbplyr_1.4.4        
[31] rlang_0.4.9          rstudioapi_0.11      farver_2.0.3        
[34] generics_0.0.2       jsonlite_1.7.1       ModelMetrics_1.2.2.2
[37] magrittr_2.0.1       Matrix_1.2-18        Rcpp_1.0.5          
[40] munsell_0.5.0        fansi_0.4.1          lifecycle_0.2.0     
[43] stringi_1.5.3        whisker_0.4          yaml_2.2.1          
[46] MASS_7.3-53          plyr_1.8.6           recipes_0.1.14      
[49] grid_3.6.3           blob_1.2.1           promises_1.1.1      
[52] crayon_1.3.4         haven_2.3.1          splines_3.6.3       
[55] hms_0.5.3            magick_2.5.2         knitr_1.30          
[58] pillar_1.4.6         reshape2_1.4.4       codetools_0.2-16    
[61] stats4_3.6.3         reprex_0.3.0         glue_1.4.2          
[64] evaluate_0.14        data.table_1.13.2    modelr_0.1.8        
[67] vctrs_0.3.4          httpuv_1.5.4         foreach_1.5.1       
[70] cellranger_1.1.0     gtable_0.3.0         assertthat_0.2.1    
[73] xfun_0.19            gower_0.2.2          prodlim_2019.11.13  
[76] broom_0.7.2          e1071_1.7-4          later_1.1.0.1       
[79] survival_3.1-8       timeDate_3043.102    iterators_1.0.13    
[82] lava_1.6.8           ellipsis_0.3.1       ipred_0.9-9