我對 R 比較陌生,無法弄清楚如何將我的for回圈變成foreach回圈。
我有幾個元素的向量,即
> hpattern
[1] "sim0_pmax.tif" "sim0_vmax.tif" "sim1_pmax.tif" "sim1_vmax.tif"
> typeof(hpattern)
[1] "character"
第一:我來自python這個詞,hpatternitem應該是一個串列,因為它是按如下方式創建的
list_h30 = data.frame(list.files(path = tr30dir, pattern=paste(depthfile,". $",sep=""), recursive = TRUE, full.names = FALSE))
hpattern <- sub(paste(".*",depthfile,sep=""), "", list_h30[,1])
為什么typeof hpattern是字符而不是串列?
第二:如果我跑
for (hpi in hpattern) {print(hpi)}
我得到
[1] "sim0_pmax.tif"
[1] "sim0_vmax.tif"
[1] "sim1_pmax.tif"
[1] "sim1_vmax.tif"
如果我跑
foreach(hpi=hpattern, .combine='c') %do% {print(hpi)}
我得到
[1] "sim0_pmax.tif"
[1] "sim0_vmax.tif"
[1] "sim1_pmax.tif"
[1] "sim1_vmax.tif"
[1] "sim0_pmax.tif" "sim0_vmax.tif" "sim1_pmax.tif" "sim1_vmax.tif"
我不明白為什么我得到最后一個輸出。
uj5u.com熱心網友回復:
正如羅蘭所說,sub回傳一個字符向量(在 中R,大多數東西都是向量)。檢查物件的另一個有用函式是str.
關于foreach:它結合了每次回圈執行的輸出。您已指定您想要一個向量 (by .combine = 'c')。
由于print回傳的每一個物件不可見,每個hpi被列印的回圈內,并且然后被組合以最終載體。將其與不列印時進行比較:
foreach(hpi=hpattern, .combine='c') %do% {hpi}
[1] "sim0_pmax.tif" "sim0_vmax.tif" "sim1_pmax.tif" "sim1_vmax.tif"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315524.html
