簡體   English   中英

R eval(predvars, data, env) object 未通過在 function 中傳遞參數找到

[英]R eval(predvars, data, env) object not found by passing a pameter in a function

我的可重現示例如下;

請不要理會計算的潛在含義(實際上沒有),因為它只是我真實數據集的摘錄;

train <- structure(list(no2 = c(25.5, 31.2, 33.4, 29.9, 31.8),
                        vv_scal = c(1.3, 1.3, 0.8, 1.1, 0.9), 
                        temp = c(-0.7, -2, 1.5, 0.4, 1.1), 
                        prec = c(0, 11, 9, 3, 0), 
                        co = c(1.6, 2.9, 3.2, 2.6, 3)), 
                        row.names = c(NA, -5L), 
                        class = c("tbl_df", "tbl", "data.frame"))


test <- structure(list(no2 = c(41.6, 41.4, 46.6, 44.7, 43.2), 
                       vv_scal = c(1.2, 1.2, 1.2, 1, 1), 
                       temp = c(0.9, 1, 0.1, 1.6, 3.8), 
                       prec = c(0, 0, 0, 0, 0), 
                       co = c(4.3, 4.3, 4.9, 4.7, 4.5)), 
                       row.names = c(NA, -5L), 
                       class = c("tbl_df", "tbl", "data.frame"))
                       
                       

forest_ci <- function(B, train_df, test_df, var_rf){
  
  # Initialize a matrix to store the predicted values
  predictions <- matrix(nrow = B, ncol = nrow(test_df))
  
  # bootstrapping predictions
  for (b in 1:B) {
    
    # Fit a random forest model
    model <- randomForest::randomForest(var_rf~., data = train_df) # not working
    #model <- randomForest::randomForest(no2~., data = train_df)   # working
    
    # Store the predicted values from the resampled model
    predictions[b, ] <- predict(model, newdata = test_df)
    
  }
  
  predictions
  
}

predictions <- forest_ci(B=2, train_df=train, test_df=test, var_rf = no2)

我收到以下錯誤消息:

Error in eval(predvars, data, env) : object 'no2' not found

我認為理解錯誤與“非標准評估”和“捕獲表達式”的概念有某種關系

http://adv-r.had.co.nz/Computing-on-the-language.html

根據一些線程的建議,這里遵循其中的一些:

如何將變量名傳遞給 function 中的參數

將變量名傳遞給 R 中的 function

我一直在嘗試使用函數的不同組合:substitute()、eval()、quote() 但沒有取得多大成功;

我知道這個主題已經在這里討論過,但到目前為止我找不到合適的解決方案;

我的目標是在 function 參數中傳遞一個變量的名稱,以便在隨機森林 model 提供的回歸(和預測)中進行評估

謝謝

嘗試使用 rlang 中的rlang ensym()inject()

forest_ci <- function(B, train_df, test_df, var_rf){
  
  y = rlang::ensym(var_rf)
  
  # Initialize a matrix to store the predicted values
  predictions <- matrix(nrow = B, ncol = nrow(test_df))
  
  # bootstrapping predictions
  for (b in 1:B) {
    
    # Fit a random forest model
    model <- rlang::inject(randomForest::randomForest(!!y~., data = train_df)) # not working
    #model <- randomForest::randomForest(no2~., data = train_df)   # working
    
    # Store the predicted values from the resampled model
    predictions[b, ] <- predict(model, newdata = test_df)
    
  }
  
  predictions
  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM