如何在 R 中使用正确的字母数字语法命名文件?

问题描述 投票:0回答:1

我正在尝试保存我的地块的 png 列表,我希望这些地块在命名时按字母数字顺序正确排序。意思是,我不希望一个名为 10Plot.png 的图比一个名为 1Plot.png 的图更早被发现。由于我正在使用 Image Magick 从图中制作 gif,因此这个顺序很重要,而且我需要编号始终为三位数。所以,我需要 1Plot.png 实际上是 001Plot.png,10Plot.png 是 010Plot.png,等等。

下面是一个简单的例子,只关注我目前如何命名 png:

plotCount <- 100 # How many plots I would like to create a name for

nameList <- list() # Empty list to just contain the names

for(i in 1:plotCount){
  nameList[i] <- paste(i, "_Plot.png", sep = "")
}

我使用 nameList 来简单地表示我需要的东西(正确命名的 png),以避免要求某人在他们的计算机上制作 100 个 png。

r export naming
1个回答
0
投票

R 是矢量化的,你不需要循环。

plotCount <- 100L

nameList <- sprintf("%03d_Plot.png", seq.int(plotCount))
head(nameList, 20)
#>  [1] "001_Plot.png" "002_Plot.png" "003_Plot.png" "004_Plot.png" "005_Plot.png"
#>  [6] "006_Plot.png" "007_Plot.png" "008_Plot.png" "009_Plot.png" "010_Plot.png"
#> [11] "011_Plot.png" "012_Plot.png" "013_Plot.png" "014_Plot.png" "015_Plot.png"
#> [16] "016_Plot.png" "017_Plot.png" "018_Plot.png" "019_Plot.png" "020_Plot.png"

创建于 2023-03-08 与 reprex v2.0.2


编辑

这是一个

for
循环解决方案,如评论中所要求的那样。还有
sprintf
.

plotCount <- 100L # How many plots I would like to create a name for
nameList <- character(plotCount) # Empty vector to just contain the names

for(i in seq.int(plotCount)){
  nameList[i] <- sprintf("%03d_Plot.png", i)
}

head(nameList, 20)
#>  [1] "001_Plot.png" "002_Plot.png" "003_Plot.png" "004_Plot.png" "005_Plot.png"
#>  [6] "006_Plot.png" "007_Plot.png" "008_Plot.png" "009_Plot.png" "010_Plot.png"
#> [11] "011_Plot.png" "012_Plot.png" "013_Plot.png" "014_Plot.png" "015_Plot.png"
#> [16] "016_Plot.png" "017_Plot.png" "018_Plot.png" "019_Plot.png" "020_Plot.png"

创建于 2023-03-08 与 reprex v2.0.2


编辑2

如果只需要一个新的、连续编号的名称,那么以下可能会更好。

注意我把

plotCount
改成只有
10L
,一个测试不需要打印100行。

plotCount <- 10L # How many plots I would like to create a name for

for(i in seq.int(plotCount)){
  png_name <- sprintf("%03d_Plot.png", i)
  # do something with this string, 
  # here I print it
  cat("This is the current PNG name:", png_name, "\n")
}
#> This is the current PNG name: 001_Plot.png 
#> This is the current PNG name: 002_Plot.png 
#> This is the current PNG name: 003_Plot.png 
#> This is the current PNG name: 004_Plot.png 
#> This is the current PNG name: 005_Plot.png 
#> This is the current PNG name: 006_Plot.png 
#> This is the current PNG name: 007_Plot.png 
#> This is the current PNG name: 008_Plot.png 
#> This is the current PNG name: 009_Plot.png 
#> This is the current PNG name: 010_Plot.png

创建于 2023-03-08 与 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.