【问题标题】:Add .PNG to relative folder path in R将.PNG添加到R中的相对文件夹路径
【发布时间】:2016-10-11 14:16:38
【问题描述】:

我正在使用 knitr 创建一个包含多个图像的降价文件。因为我不想每次都输入路径,所以我希望它是相对的。 mainDir <- ~/Documents/R/Images/ subDir <- Logo color <- blue

现在我想添加“.png”来打印实际图像。而且我不想将颜色更改为&lt;- blue.png,因为我在代码的其他部分使用了变量“蓝色”。 img1 <- rasterGrob(as.raster(readPNG(file.path(mainDir, subDir, color, ".png"))), interpolate = FALSE)

我收到以下错误: readPNG(file.path(mainDir, subDir, img, ".png")) 中的错误: 无法打开 /Documents/R/Images/Logo/blue/.png

如何删除最后一个“/”,使其变为“blue.png”而不是 blue/.png?

【问题讨论】:

    标签: r knitr r-markdown


    【解决方案1】:

    怎么样:

    mainDir <- "~/Documents/R/Images" 
    subDir <- "Logo"
    color <- "blue`
    file.path(mainDir, subDir, paste(color, ".png",sep=""))
    

    结果: "~/Documents/R/Images/Logo/blue.png"

    【讨论】:

      【解决方案2】:

      您可以使用paste 函数将文件扩展名连接到路径字符串。

      img1 &lt;- rasterGrob(as.raster(readPNG(paste(file.path(mainDir, subDir, color), ".png", sep = ""))), interpolate = FALSE)

      http://stat.ethz.ch/R-manual/R-patched/RHOME/library/base/html/paste.html

      另外,您不需要 mainDir &lt;- "~/Documents/R/Images" 上的尾随 /,因为添加子目录时它会被复制。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-02
        • 2019-12-22
        • 2021-07-24
        • 2011-04-12
        • 1970-01-01
        相关资源
        最近更新 更多