如何在R的for循环中使用paste修改照片的EXIF元数据
R动态拼接exiftool命令的修复方案
问题根源
- 循环遍历逻辑错误:当前for循环遍历的是
df$pathname的字符串值,不是行下标,因此df$S[i]无法匹配到对应行的S列取值 - 变量解析错误:
x、i被写在引号内部,R会将其识别为普通字符串而非变量,不会动态替换为迭代值
修复后代码
方案1:按行索引遍历(推荐,逻辑更稳定)
for (i in seq_len(nrow(df))) { img_path <- df$pathname[i] comment_val <- df$S[i] # 变量放在引号外部,用逗号分隔拼接 sysCommand <- paste0("exiftool -Comment=", comment_val, " ", img_path) system(sysCommand) }
方案2:沿用路径遍历逻辑的修改版
for (img_path in df$pathname) { # 按路径匹配对应的S列取值 comment_val <- df$S[df$pathname == img_path] sysCommand <- paste0("exiftool -Comment=", comment_val, " ", img_path) system(sysCommand) }
注意事项
如果S列的取值包含空格、特殊符号,建议给Comment值外层包裹单引号,避免系统命令解析报错:
sysCommand <- paste0("exiftool -Comment='", comment_val, "' ", img_path)
内容的提问来源于stack exchange,提问作者Rogue
相关产品推荐
相关产品推荐

