2016-10-24 53 views
2

我有幾個隨機森林公式命名forest.1,forest.2,forest.3,等想讀他們一個個用「爲」重複,例如:如何識別名稱爲redomforest fomula的數字?

for(i in 1:20){ 
    model = forest.i 
    predict.y = predict(model, test.x) 
} 

當然,森林.i(我從1到20)不能被識別爲20個公式。我能做些什麼來使它工作?謝謝!

+0

類似:http://stackoverflow.com/questions/15270482/string-to-variable-name-in-r – krlmlr

回答

2

您可以使用功能get,例如, model <- get(sprintf("forest.%i", i))。這將創建一個字符串,例如forest.1並嘗試使用該名稱獲取對象。

+0

謝謝!有用! – Jessie

0

嘗試把它們放入一個列表第一:

forests <- list(
    forest.1, 
    forest.2, 
    forest.3, 
    ..., 
    forest.20 
) 

(在點填寫。)然後,你可以簡單地做

for (model in forests) { 
    ... # your code 
} 

如果你不想鍵入20名單條目,創建一個字符向量,其值爲"forest.1",直到"forest.20",並使用mget

+0

謝謝!有用! – Jessie