繁体   English   中英

在单词之间粘贴输入名称以使用 write.table 进行保存

[英]paste input name between words for save it using write.table

我是 R 的超级新手,由于我的工作学位,我已经为自己学习了几个星期。 我几乎完成了我需要的统计分析,但它是通过一个丑陋而凌乱的代码,即对几个数据帧重复大量代码,以应用不同的统计测试,保存结果等。现在,为了个人利益,想把这个写得更好,但我完全陷入了我的无知,真的需要推动才能得到这个想法,拜托了。 例如,我想创建一个函数来测量我使用的所有数据表的相关性,并使用输入名称作为输出名称的一部分将这些结果保存为表。 我的意思是,如果我们有 iris 数据但在不同季节测量,例如 iris_fall、iris_winter、iris_spring 和 iris_summer,在对每个数据应用cor(X)方法后,我想将这些结果保存为类似于“mCoriris_fall.txt”的表格、“mCoriris_winter.txt”、“mCoriris_spring.txt”和“mCoriris_summer.txt”。 我现在无用的代码说:

cor_PQ<-function(X) {
  cor_PQ<-cor(X, use="pairwise.complete.obs")
  return(cor_PQ)
}
savecor<-function(t) {
  outputname<-(paste0("mCor",t)) #HOW DO I CALL THE NAME OF THE INPUT? t is cor_PQ result matrix.
  savecor<-write.table(t, file=paste0(outputname,".txt"))
  return(savecor)
}
cor_PQ(Iris_fall)

我希望获得cor结果并将其保存为我的工作区中的表格,使用输入名称作为输出名称的一部分。 我知道这是 2 个独立的函数,写表的函数应该在cor(x)函数内部,但我无法理解。 我读了很多书,但我无法完全记在脑海中。 感谢任何可以帮助我的人。 问候。

直到这里它已经解决了......但是在用我的 14 个数据框列出一个列表以应用cor和其他方法之后, write.table函数覆盖了 1 个单个文档上的 14 个cor结果。 这是我的代码。

PQ_files<-list.files(path="C:/Users/Sol/Documents/ProyectoTítulo/CalidadAgua/Matrices/Regs",pattern="\\_PQ.txt")

PQ_data<-lapply(PQ_files, read.table)

names(PQ_data)<-gsub("\\_PQ.txt","", PQ_files)

PQ_data

cor_PQ<-function(X) {
  cor_PQ<-cor(X, use="pairwise.complete.obs")
  outputname.txt<-paste0("mCor",deparse(substitute(X)),".txt")
  write.table(cor_PQ, file=outputname.txt)
  outputname.pdf<-paste0("Cor",deparse(substitute(X)),".pdf")
  pdf(outputname.pdf)
  plot(X)
  dev.off()
  return(cor_PQ)
}

for (i in seq_along(PQ_data)){
  Correlaciones<-lapply(PQ_data,cor_PQ)
  }

Correlaciones

在 SUM 上:似乎工作得几乎很好,直到write.tableplot(x)用名称mCor[[i]]CorX[[i]]覆盖了我的PQ_data上的 14 个数据帧的输出。 我应该以某种方式定义 [i] 以使每个结果都具有正确的名称吗? 此外,当我最后运行Correlaciones时,我可以在一个数据帧中看到 14 个数据帧的cor结果,但我不知道如何正确拆分它们。 我想快到了。 再次感谢!

您可以组合这两个函数并使用deparse substitute将输入名称作为字符串

cor_PQ <- function(X) {
   cor_PQ<-cor(X, use="pairwise.complete.obs")
   outputname<- paste0("mCor",deparse(substitute(X)), ".txt")
   write.table(t, file=outputname)
   return(cor_PQ)
}

然后打电话

cor_PQ(Iris_fall)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM