如何很好地使用foreach函数?

时间:2019-02-18 14:47:06

标签: r

我想在R中使用foreach()函数。

这是我的示例代码。

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)))) 
}

无需修改整个代码,我想更改代码

foreach(VAR=age) or foreach(VAR=bili)..。等

但是在错误消息中,此代码将"age"视为对象。

如何正确运行此代码?

1 个答案:

答案 0 :(得分:1)

您需要使用foreach(VAR="age")定义foreach,然后以data_na[,VAR]代替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)))) 
}