Loop for compiling a DT

129 views Asked by At

As I am absolutely new in R (and in coding) I would like to ask a feedback about this part of a code I wrote

setwd("C:/Users/dd16722/R/Raman/Data/Raw")

#Import LW spectra
listLW <- list.files(path = ".", pattern = "LW")
numLW <- as.integer(length(listLW))

# Import the first file
library(data.table)
DT_final_LW <- fread(file = listLW[1])
setnames(DT_final_LW, c("Raman shift (cm-1)", listLW[1]))

# Loop over the rest of the files and use cbind to merge them into 1 DT
for(file in setdiff(listLW, listLW[1])) {
  DT_temp_LW <- fread(file)
  setnames(DT_temp_LW, c("Raman shift (cm-1)", file))
  DT_final_LW <- cbind(DT_final_LW, DT_temp_LW)
}

#Plot raw spectra
plot(unlist(DT_final_LW[,1]), unlist(DT_final_LW[,2]), type = "l", xaxs="i", yaxs="i", main="Raman spectra", xlab="Raman shift (cm-1)", ylab="Intensity")

for(i in 1:(numLW)) {
  lines((DT_final_LW[[2*i-1]]), (DT_final_LW[[2*i]]))
}

# Temperature-excitation line correction
laser = 532

DT_final_LW_corr=DT_final_LW
for(i in 1:(numLW*2)){
  if (!i %% 2==FALSE) 
    DT_final_LW_corr[[i]] <- DT_final_LW[[i]]
  if (!i %% 2==TRUE)
    DT_final_LW_corr[[i]] <- DT_final_LW[[i]]*((10^7/laser)^3*(1-exp(-6.62607*10^(-34)*29979245800*DT_final_LW[[i-1]]/(1.3806488*10^(-23)*293.15)))*DT_final_LW[[i-1]]/((10^7/laser)-DT_final_LW[[i-1]])^4)
}

#Plot corrected spectra
plot(unlist(DT_final_LW_corr[,1]), unlist(DT_final_LW_corr[,2]), type = "l", xaxs="i", yaxs="i", main="Raman spectra", xlab="Raman shift (cm-1)", ylab="Intensity")

It works for my purpose. I would like to know if there is a more correct way to run such a operation. Many thanks in advance for your contribution.

0

There are 0 answers