我正在尝试对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
或sapply
或lapply
函数来缩短代码。有谁知道怎么做?
感谢您的帮助!
大卫
答案 0 :(得分:2)
我们可以使用lapply
轻松完成此操作,方法是将感兴趣的列(&#39; nm1&#39;)和replace
的值循环到1,其中&#39; only0& #39;是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")
答案 1 :(得分:0)
你可以尝试,
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")