r dplyr - 读取文件列表并使用文件名作为变量 [英] r dplyr - read list of files and use filename as a variable

查看:36
本文介绍了r dplyr - 读取文件列表并使用文件名作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用每个文件的名称替换 image_annotate 下面的文本".

I would like to replace the "Text" below in image_annotate by the name of each file.

library(dplyr)
library(purrr)
library(magick)

list.files(path = "", pattern = "*.png", full.names = T) %>% 
      map(image_read) %>%
      lapply(. %>% image_annotate("Text")) %>%
      image_join() %>% 
      image_animate(fps=1) %>% 
      image_write("animated.gif")

推荐答案

我认为这应该可行.由于您获得了有关文件名的信息并将其传递给 image_read 但还想将此信息用于另一个函数 (image_annotate),因此您可以轻松地将两者放在一个map 中的函数.如果您不想将整个路径作为注释,只需将 image_annotate(fnme) 替换为 image_annotate(stringr::str_extract(string = fnme, pattern = "(?<=(/|\\\\)).+(?=\\.png)")) 匹配 /\ 之间的任何内容.png (假设您不想要结尾,否则只需删除前瞻 (?=\\.png).

I think that this should work. Since you get the information about the filename and pass it to the image_read but want to use this information also for another function (image_annotate), you can easily put the two in a function within map. If you don't want the whole path as annotation, just replace image_annotate(fnme) by image_annotate(stringr::str_extract(string = fnme, pattern = "(?<=(/|\\\\)).+(?=\\.png)")) which matches anything between / or \ and .png (assuming that you don't want the ending, else just remove the lookahead (?=\\.png).

library(dplyr)
library(purrr)
library(magick)

list.files(path = "", pattern = "*.png", full.names = T) %>% 
      map(function(fnme) {
          image_read(fnme) %>% image_annotate(fnme)
      }) %>%
      image_join() %>% 
      image_animate(fps=1) %>% 
      image_write("animated.gif")

这篇关于r dplyr - 读取文件列表并使用文件名作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆