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

时间:2016-08-22 13:47:22

标签: r function output naming r-raster

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

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

我试过

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

不要列出清单(如果你不能帮忙,请使用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")
}

答案 2 :(得分:0)

如果我理解你的问题是正确的,你想使用对象的名称作为文件名的一部分。你可以使用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())的替代版本。此代码从目录中读取文件并使用前缀&#34; df _&#34;保存它们。在名为&#34; mynewfiles&#34;。

的目录中
# 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")
}