This is a specialist thing -- the xrdml format is a common way of storing the results of X-Ray Diffraction scans (we use a Panalytical Aeris).

There are two versions of the code:

  1. xrdml2df() to make a data frame but not a csv file
  2. xrdml2csv() to make a csv file but not a data frame

Probably these could be combined in a later version, with the type of output specified by the function options . You need to bring your own xrdml file(s)!

1. xrdml to data frame

xrdml2df <- function(xfile,
                     xdir = "wd"
                     ) {
  if(xdir == "wd") {
    xdir <- getwd()
    }
  xrdmlRaw <- readLines(paste0(xdir, xfile))
  twothet0 <- grep("2Theta", xrdmlRaw)
  beg0 <- xrdmlRaw[twothet0 + 1]
  beg0 <- gsub("\t\t\t\t\t<startPosition>", "", beg0)
  beg0 <- gsub("</startPosition>", "", beg0)
  beg0 <- as.numeric(beg0)
  end0 <- xrdmlRaw[twothet0 + 2]
  end0 <- gsub("\t\t\t\t\t<endPosition>", "", end0)
  end0 <- gsub("</endPosition>", "", end0)
  end0 <- as.numeric(end0)
  c0 <- grep("<counts", xrdmlRaw)
  xrdmlRaw[c0] <- gsub('\t\t\t\t<counts unit="counts">', "", xrdmlRaw[c0])
  xrdmlRaw[c0] <- gsub("</counts>", "", xrdmlRaw[c0])
  counts <- as.numeric(unlist(strsplit(xrdmlRaw[c0], " ")))
  counts2theta <-
    data.frame(Angle = seq(beg0, end0, ((end0 - beg0) / (length(counts) - 1))),
    Counts = counts)
  rm(list = c("xrdmlRaw","twothet0","beg0","end0","c0","counts"))
  return(counts2theta)
}

2. xrdml to csv

xrdml2csv <- function(xfile,
                     xdir = "wd",
                     toscreen = FALSE
                     ) {
  if(xdir == "wd") {
    xdir <- getwd()
    }
  xrdmlRaw <- readLines(paste0(xdir, xfile))
  twothet0 <- grep("2Theta", xrdmlRaw)
  beg0 <- xrdmlRaw[twothet0 + 1]
  beg0 <- gsub("\t\t\t\t\t<startPosition>", "", beg0)
  beg0 <- gsub("</startPosition>", "", beg0)
  beg0 <- as.numeric(beg0)
  end0 <- xrdmlRaw[twothet0 + 2]
  end0 <- gsub("\t\t\t\t\t<endPosition>", "", end0)
  end0 <- gsub("</endPosition>", "", end0)
  end0 <- as.numeric(end0)
  c0 <- grep("<counts", xrdmlRaw)
  xrdmlRaw[c0] <- gsub('\t\t\t\t<counts unit="counts">', "", xrdmlRaw[c0])
  xrdmlRaw[c0] <- gsub("</counts>", "", xrdmlRaw[c0])
  counts <- as.numeric(unlist(strsplit(xrdmlRaw[c0], " ")))
  counts2theta <-
    data.frame(Angle = seq(beg0, end0, ((end0 - beg0) / (length(counts) - 1))),
    Counts = counts)
  cfile <- paste0(substr(xfile,1,str_locate(xfile,".xrdml")[1]),"csv")
  write.csv(counts2theta, file = cfile, row.names = FALSE)
  rm(list = c("xrdmlRaw","twothet0","beg0","end0","c0","counts"))
  if(toscreen==TRUE) return(counts2theta)
}

CC-BY-SA • All content by Ratey-AtUWA. My employer does not necessarily know about or endorse the content of this website.
Created with rmarkdown in RStudio using the cyborg theme from Bootswatch via the bslib package, and fontawesome v5 icons.