我正在使用 R 版本 4.0.4 的 MacOS Big Sur 11.6 (2021-02-15)
我試圖在 for 回圈中使用 paste() 但我需要 paste 函式中的值隨著每次迭代而改變。
我有一個這樣的資料框:
pathname S
1 user/folder/photo1 A
2 user/folder/photo2 B
3 user/folder/photo3 C
我正在嘗試將 EXIF 評論標簽添加到我照片的元資料中。我希望 Comment 標簽根據 S 列值進行更改。我有這樣的代碼:
for(i in df$pathname){
x <- df$S[i]
sysCommand <- paste("exiftool -Comment=x i")
system(sysCommand)
}
粘貼函式中的輸入(即 x 和 i)應該隨著它通過串列而改變。
感謝您的幫助!
uj5u.com熱心網友回復:
擴展@Greg 對粘貼功能的出色回答。您在訪問資料框中的資料的邏輯中存在一些缺陷。
也是paste一個向量化函式,它更容易制作系統命令的向量,然后只需使用回圈來執行命令。這節省了處理下標的作業。
data<- read.table(header=TRUE, text=" pathname S
user/folder/photo1 A
user/folder/photo2 B
user/folder/photo3 C")
#paste is vectorized function
# create a list of all of the requested system commands
commands <-paste0("exiftool -Comment=", data$S, " ", data$pathname)
#loop through the vectors of command
for (i in commands) {
print(i) #debugging
system(i)
}
uj5u.com熱心網友回復:
你哪里出錯了
你的解釋paste()有問題。此函式采用 R物件并連接它們的字串表示形式。
所以給出
name <- "Rogue"
然后是代碼
paste("Hi name!", " How are you?")
將簡單地連接字串物件"Hi name!"并" How are you?"產生
[1] "Hi name! How are you?"
要在 中替換name,必須使用name 物件
paste("Hi ", name, "!", " How are you?")
# ^^^^
獲得
[1] "Hi Rogue! How are you?"
解決方案1:正確使用paste()
由于意見正確建議,正確使用paste()會
# ...
sysCommand <- paste("exiftool -Comment=", x, " ", i, sep = "")
# ^^^^^^^^
# Avoid unwanted spaces.
# ...
小心包含引數sep = "",從而避免像"exiftool -Comment= A 1". 每個結果應如下所示:
[1] "exiftool -Comment=A 1"
筆記
該paste0()函式會自動省略多余的空格,因此不需要sep = "".
解決方案 2:glue包
為了使事情按您預期的方式作業,您可以使用該glue包。
# ...
sysCommand <- glue::glue("exiftool -Comment={x} {i}")
# ...
小心地“擁抱”每個變數名{ }。每個結果應該看起來像
exiftool -Comment=A 1
一個glue也是普通字串的物件。
筆記
正如我在評論中提到的
You've extracted your data incorrectly with
for(i in df$pathname)anddf$S[i]. When you useiindf$pathname, you're iterating withiover the strings"user/folder/photo1","user/folder/photo2", and so forth. By contrast,df$S[i]expects a number within the[ ], as it attempts to take the value in theith place of columnS. Since it can't interpret a string like"user/folder/photo1"as anumericindex, the operationdf$S[i]returns anNAvalue...whichpaste()interprets as the string"NA".
your original code also erred logically when accessing the data in df. The nifty answer by @dave2e offers a cleanly vectorized solution to this error.
That said, your correction does well in fixing this issue
for(i in 1:length(df$pathname)){
#for each photo
x <- df$S[i]
pathname <- df$pathname[i]
syscommand <- paste("exiftool -Comment=", site, " ", pathname, sep = "")
system(syscommand)
}
and it retains the structure of your original loop. I'm happy to hear it works!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336894.html
