R Code examples
R code snippets for table manipulation
In R language dplyr and tidyr are two useful packages for handling and manipulating tables.
R code snippet to join two tables
| Subject_ID | Files | Session |
|---|---|---|
| S001 | filename1.ext | 1 |
| S002 | NA | NA |
| S003 | filename1.ext | 1 |
| S003 | filename2.ext | 1 |
| S003 | filename3.ext | 2 |
| S003 | filename4.ext | 2 |
| Subject_ID | Scan_Date | Modality | Sex | Age_years | Weight_kg | Exp_Group | Scanner_Model | Notes | Files | Session |
|---|---|---|---|---|---|---|---|---|---|---|
| S001 | 01/01/2023 | MRI | M | 25 | 70.00 | Control | Siemens | None | filename1.ext | 1 |
| S002 | 02/01/2023 | fMRI | F | 26 | 72.04 | Exp | Siemens | Motion artifact | NA | NA |
| S003 | 03/01/2023 | DTI | M | 27 | 75.00 | Exp | Philips | High noise | filename1.ext | 1 |
| S003 | 03/01/2023 | DTI | M | 27 | 75.00 | Exp | Philips | High noise | filename2.ext | 1 |
| S003 | 03/01/2023 | DTI | M | 27 | 75.00 | Exp | Philips | High noise | filename3.ext | 2 |
| S003 | 03/01/2023 | DTI | M | 27 | 75.00 | Exp | Philips | High noise | filename4.ext | 2 |
In more complex settings, it is possible to specify the expected relationship between two tables (e.g., if each row from table x is expected to have a match in table y, etc.) see mutate-joins.
R code to convert from wide to long format
library(tidyr)
library(dplyr)
# Make an example table
tbl_wide <- data.frame(
Subject_ID = c("S001", "S002", "S003", "S004"),
Test_A = c(5.4, 6.1, 7.3, 4.8),
Test_B = c(3.2, 5.8, 6.5, 4.1)
)
# Convert to long format
tbl_long <- tbl_wide %>%
pivot_longer(cols = c(Test_A, Test_B), names_to = "Test",
values_to = "Value")R code to convert from long to wide format
R code snippet to create JSON files from a table
In this example each row of a table with metadata is transformed into a JSON file. The R package jsonlite offers several encoding formatting options.
- A dummy metadata table
| id | img_location | sex | condition | treatment |
|---|---|---|---|---|
| subject_04 | dummyfolder/subject_04_imgfile.tiff | female | A | control |
| subject_93 | dummyfolder/subject_93_imgfile.tiff | female | B | control |
| subject_12 | dummyfolder/subject_12_imgfile.tiff | female | B | treat_3 |
| subject_65 | dummyfolder/subject_65_imgfile.tiff | male | B | control |
| subject_98 | dummyfolder/subject_98_imgfile.tiff | female | A | treat_1 |
| subject_71 | dummyfolder/subject_71_imgfile.tiff | male | A | treat_3 |
| subject_24 | dummyfolder/subject_24_imgfile.tiff | female | B | control |
- The rows converted to JSON
The following line can be added in the loop to save the row as a JSON file with the same name as the images listed in the table
