R 在输出中自动使用数据 table 名称

R automatically use data table name in output

我有一个循环,我想通过将 rasnames 中的元素与“_unc.tif”

中的元素组合来创建输出文件名的字符向量
rasnames = list("Wheat","Sbarley","Potato","OSR","fMaize") 

我试过了

for (i in 1:length(rasnames)){
  filenm <- rasnames[i]
  filenm <- c(filenm,"_unc",".tif")
 }

您应该使用 paste(),而不是 c()c() 创建一个字符串列表,而不是一个连接的字符串:

paste(filenm,"_unc",".tif",sep="")

如果我理解你的问题是正确的,你想使用对象的名称作为文件名的一部分。您可以使用 deparse(substitute(obj)):

    ftest <- function(df) {
paste0(deparse(substitute(df)), ".tif")
}

ftest(iris)

# Output:
# [1] "iris.tif"

见: How to convert variable (object) name into String

如果您想使用字符串列表作为文件名:

ftest2 <- function(lst) {
  for (i in 1:length(lst)) {
    filename <- lst[[i]]
    filename <- paste0(filename, ".tif")
    print(filename)
  }
}
rasnames = list("Wheat","Sbarley","Potato","OSR","fMaize")
ftest2(rasnames)

# Output:
# [1] "Wheat.tif"
# [1] "Sbarley.tif"
# [1] "Potato.tif"
# [1] "OSR.tif"
# [1] "fMaize.tif"

这是一个不使用 deparse(substitute()) 的替代版本。这段代码从一个目录中读取文件,并使用前缀 "df_" 将它们保存在名为 "mynewfiles".

的目录中
# create some text files in your working directory using the the "iris" data
write.table(iris, file = "test1.txt", sep = "\t")
write.table(iris, file = "test2.txt", sep = "\t")

# get the file names
myfiles <-  dir(pattern = "txt")

# create a directory called "mynewfiles" in your working directory 
# if it doesn't exists

if (!file.exists("mynewfiles")) {
  dir.create("mynewfiles")
}

for (i in 1:length(myfiles)) { 
  dftmp <- read.table(myfiles[i], header = TRUE, sep = "\t")
  # insert code to do something with the data frame...
  filename <- paste0("df_", myfiles[i])
  print(filename)
  write.table(dftmp, file = file.path("mynewfiles", filename), sep = "\t")
}

不要列出清单(或者,如果您无法帮助,请使用 unlist

rasnames = c("Wheat","Sbarley","Potato","OSR","fMaize") 

制作输出名称向量:

outnames = paste0(rasnames, "_unc.tif")

for (i in 1:length(rasnames)){
  filenm <- outnames[i]
}

或者:

for (i in 1:length(rasnames)){
  filenm <- paste0(rasnames[i], "_unc.tif")
}