Skip to content

Instantly share code, notes, and snippets.

@DannyArends
Last active June 15, 2023 12:55
Show Gist options
  • Save DannyArends/f11c215d9fe7c62a96cc470661ec2aa1 to your computer and use it in GitHub Desktop.
Save DannyArends/f11c215d9fe7c62a96cc470661ec2aa1 to your computer and use it in GitHub Desktop.
# Author : Danny Arends
# Purpose : create an MRI table from the format provided by our MRI reader
months <- rbind(c("Jan",31),c("Feb",28),c("Mar",31),c("Apr",30),c("May",31),c("Jun",30),
c("Jul",31),c("Aug",31),c("Sep",30),c("Oct",31),c("Nov",30),c("Dec",31))
createMRItable <- function(MRIdata, description){
dates <- strsplit(unlist(lapply(strsplit(as.character(MRIdata[,"TimeDateDura"]),";"),"[",1))," ") # Get the malformed dates
MRIdata[,"TimeDateDura"] <- unlist(lapply(dates, function(x){ # Transform to DD/MM/YY
monthNumber <- which(months[,1]==x[2])
paste(gsub(",","",x[3]), monthNumber, x[4],sep="/")
}))
for(x in 1:nrow(MRIdata)){
bDay <- as.character(description[as.character(MRIdata[x,"Label"]), "W-dat"]) # Date of birth
mDay <- as.character(MRIdata[x, "TimeDateDura"]) # Date of measurement
daysDiff <- as.numeric(round(difftime(strptime(mDay, format = "%d/%m/%Y"), strptime(bDay, format = "%d.%m.%Y"), units="days")))
if(length(daysDiff) == 0) daysDiff<- 666 # If one of the dates is missing use 666
cat(bDay, mDay, daysDiff, "\n")
MRIdata[x, "Age"] <- daysDiff
}
animals <- unique(as.character(MRIdata[,"Label"]))
timepoints <- unique(as.character(MRIdata[,"Age"]))
fat <- matrix(NA, length(animals), length(timepoints), dimnames=list(animals, timepoints))
lean <- matrix(NA, length(animals), length(timepoints), dimnames=list(animals, timepoints))
for(tp in timepoints){
for(animal in animals){
ii <- which(MRIdata[,"Label"] == animal & MRIdata[,"Age"] == tp)
if(length(ii) > 0){
fat[animal, tp] <- mean(MRIdata[ii,"Fat"])
lean[animal, tp] <- mean(MRIdata[ii,"Lean"])
}
}
}
return(list(fat, lean))
}
mridata <- read.table("mri_file.txt") # file from the MRI machine with multiple measurements
annotation <- read.table("breedingfilefromdahlem.txt") # animalID coupled to birthday
tables <- createMRItable(mridata, annotation)
fat <- tables[[1]] # Fat measurements per animal per timepoints
lean <- tables[[2]] # lean measurements per animal per timepoint
write.table(fat, "fat.txt", sep = "\t", quote = FALSE)
write.table(lean, "lean.txt", sep = "\t", quote = FALSE)
write.table(fat / lean, "fatlean.txt", sep = "\t", quote = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment