使用 sapply 或 R 中的循环重复条件更改

Repeated conditional change with sapply or a loop in R

我正在尝试对 R 中的 11 列列表进行条件更改。我的条件始终相同 survey$only0 == 1。我写了下面的代码:

survey$w.house[survey$only0 == 1] <- 1
survey$w.inc[survey$only0 == 1] <- 1
survey$w.jobs[survey$only0 == 1] <- 1
survey$w.com[survey$only0 == 1] <- 1
survey$w.edu[survey$only0 == 1] <- 1
survey$w.env[survey$only0 == 1] <- 1
survey$w.health[survey$only0 == 1] <- 1
survey$w.satisf[survey$only0 == 1] <- 1
survey$w.safe[survey$only0 == 1] <- 1
survey$w.bal[survey$only0 == 1] <- 1
survey$w.civic[survey$only0 == 1] <- 1

我的代码运行良好,但我想使用 loop 或函数 sapplylapply 来缩短我的代码。有谁知道怎么做吗?

感谢您的帮助!

大卫

我们可以通过循环遍历感兴趣的列 ('nm1') 使用 lapply 轻松地做到这一点,并且 replace 它的值到 1 其中 'only0' 是1.

survey[nm1] <- lapply(survey[nm1], function(x) replace(x, survey$only0==1, 1))

或者如@Vlo 所述,不需要匿名函数调用

survey[nm1] <- lapply(survey[nm1], replace, list = survey$only0==1, values=1)

哪里

nm1 <- c("w.house", "w.inc", "w.jobs", "w.com", "w.edu", "w.env",
     "w.health", "w.satisf", "w.safe", "w.bal", "w.civic")

你可以试试,

survey[survey$only0 == 1, cols] <- 1

其中 cols 是您要检查其条件的列。

cols <- c("w.house", "w.inc", "w.jobs", "w.com", "w.edu", "w.env",
            "w.health", "w.satisf", "w.safe", "w.bal", "w.civic")