Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 我是初学者。如何将代码应用于所有文件并保存新的txt?_R_Loops_Write.table - Fatal编程技术网

R 我是初学者。如何将代码应用于所有文件并保存新的txt?

R 我是初学者。如何将代码应用于所有文件并保存新的txt?,r,loops,write.table,R,Loops,Write.table,我有这个平滑光谱的代码 list_tot <- list.files(path = ".", pattern="*.txt") num <- as.integer(length(list_tot)) library(data.table) DT_final_tot <- fread(file = list_tot[1]) setnames(DT_final_tot, c("Raman shift (cm-1)", list_tot[1])) x <-DT_final

我有这个平滑光谱的代码

list_tot <- list.files(path = ".", pattern="*.txt")
num <- as.integer(length(list_tot))


library(data.table)
DT_final_tot <- fread(file = list_tot[1])
setnames(DT_final_tot, c("Raman shift (cm-1)", list_tot[1]))

x <-DT_final_tot[[1]]
y <-DT_final_tot[[2]]

smooth_spectra <- smooth.spline(x,y, spar = NULL) 
plot(x,y, type = "l", main="raw spectra", col="green") 
lines(smooth_spectra,type = "l") 
plot(smooth_spectra,type = "l", main="smooth spectra ")
我已经在文件夹的第一个文件中应用了代码!如何将其应用于所有文件,以及如何将平滑的光谱保存为txt。档案

library(data.table)
list_tot <- list.files(path = ".", pattern="*.txt")
num <- as.integer(length(list_tot))

for(fname in list_tot) {
  DT_final_tot <- fread(file = fname)
  setnames(DT_final_tot, c("Raman shift (cm-1)", fname))

  x <-DT_final_tot[[1]]
  y <-DT_final_tot[[2]]

  smooth_spectra <- smooth.spline(x,y, spar = NULL) 
  plot(x,y, type = "l", main="raw spectra", col="green") 
  lines(smooth_spectra,type = "l") 
  plot(smooth_spectra,type = "l", main="smooth spectra ")

  dump(c("smooth_spectra"), file=paste0(tools::file_path_sans_ext(fname), "_smoothed", ".csv"))
}

您应该引入for循环来迭代列表。它将平滑光谱保存在文件中,名称与输入文件相同,前缀为平滑,扩展名为.csv。

这是什么语言?请适当标记。谢谢。我更改了write.table中的write.csv和.txt中的.csv,因为我需要txt。无论如何,我有一个错误:as.data.frame.defaultx[[i]]中的错误,可选=TRUE,stringsAsFactors=stringsAsFactors:无法将类smooth.spline强制为数据。frame@AlbertoCaracciolo您想如何存储它?我已经更新了答案。我喜欢将它存储在一个名为“平滑”的新文件夹中,例如,在同一个目录中!