简体   繁体   中英

Apply NA to the rows that meet a condition in R

I have a data.frame like such:

 set.seed(126)
df <- data.frame(a=sample(c(1:100, NA), 10), b=sample(1:100, 10), c=sample(1:100, 10))

    a  b  c
1  65 48 19
2  46 15 80
3  NA 47 84
4  68 34 46
5  23 75 42
6  92 87 68
7  79 28 48
8  84 55  9
9  28 43 38
10 94 99 77
> 

I'd like to write a function that transforms all values in all columns to NA if df$a is NA However, I don't want to just assign b and c the value of NA , rather I would like a function that turns all columns in the data.frame to NA if the condition is.na(a) is met, no matter the number of columns.

I think you are just looking for

df[is.na(df$a), ] <- NA
#     a  b  c
# 1  65 48 19
# 2  46 15 80
# 3  NA NA NA
# 4  68 34 46
# 5  23 75 42
# 6  92 87 68
# 7  79 28 48
# 8  84 55  9
# 9  28 43 38
# 10 94 99 77

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM