首页 > 解决方案 > How can I use foreach function well?

问题描述

I would like to use foreach() function in R.

Here's my example code.

library(randomForestSRC)
library(dplyr)
library(ROCR)
library(doParallel)

data(pbc, package="randomForestSRC")

data_na <- na.omit(pbc)
data_na <- data_na %>% dplyr::select(-days)

foreach(VAR=age) %do% {
  data_na <- data_na %>%
    mutate(Q4 = ifelse(data_na[,"VAR"]<=unname(quantile(data_na[,"VAR"], 0.25)), 0,
                ifelse(data_na[,"VAR"]<=unname(quantile(data_na[,"VAR"], 0.50)), 1,
                ifelse(data_na[,"VAR"]<=unname(quantile(data_na[,"VAR"], 0.75)), 2, 3)))) 
}

Without modifying the whole code, I want to change the code

foreach(VAR=age) or foreach(VAR=bili)... etc.

But in the error message, this code consider "age" as an object.

How can I run this code without error?

标签: r

解决方案


您需要定义 foreach ,foreach(VAR="age")然后调用data_na[,VAR]as data_na[,"VAR"]

此外,您可以将变量定义为 foreach,如下所示:

vars <- c("age", "bili") # you can include more variables here

foreach(i = 1:length(vars)) %do% {
  VAR = vars[i]
  data_na <- data_na %>%
    mutate(Q4 = ifelse(data_na[,VAR]<=unname(quantile(data_na[,VAR], 0.25)), 0,
                       ifelse(data_na[,VAR]<=unname(quantile(data_na[,VAR], 0.50)), 1,
                              ifelse(data_na[,VAR]<=unname(quantile(data_na[,VAR], 0.75)), 2, 3)))) 
}

推荐阅读