Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

r - changing multiple column values given a condition in dplyr

I'm looking to find a simple way to do something like the following but with dplyr, essentially just replacing the values in 3 columns with NA when the condition is met.

dta[dta$na.ind == 1, c('x1', 'x2', 'x3')] <- NA

The only method I can think of using dplyr is the following, but I feel there should be a simpler way

dta <- dta %>% 
    mutate(x1 = ifelse(na.ind == 1, NA, x1),
           x2 = ifelse(na.ind == 1, NA, x2),
           x3 = ifelse(na.ind == 1, NA, x3))

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use mutate_at and pass the columns x1,x2,x3 to .vars parameter:

dta <- data.frame(na.ind = 1:3, x1 = 2:4, x2 = 2:4, x3 = 2:4, x4 = 2:4)
dta
#  na.ind x1 x2 x3 x4
#1      1  2  2  2  2
#2      2  3  3  3  3
#3      3  4  4  4  4

dta %>% mutate_at(.vars = c("x1", "x2", "x3"), funs(ifelse(na.ind == 1, NA, .)))
#  na.ind x1 x2 x3 x4
#1      1 NA NA NA  2
#2      2  3  3  3  3
#3      3  4  4  4  4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...