for example, I have a data frame as follows:
df<- data.frame( A= c(1:10),B=c(11:20),C=c(21,30))
I want to replace the value from column C which is greater than 21 and replace it with NA. in addition at the same time, I want to do the same with column B for the values greater than 18.
the expected results are something like
Something like this would work:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df<- data.frame( A= c(1:10),B=c(11:20),C=c(21,30))
replace_with_na <- function(vector, value){
vector[vector > value] <- NA_real_
vector
}
df %>%
dplyr::mutate(B = replace_with_na(B, 18),
C = replace_with_na(C, 21))
#> A B C
#> 1 1 11 21
#> 2 2 12 NA
#> 3 3 13 21
#> 4 4 14 NA
#> 5 5 15 21
#> 6 6 16 NA
#> 7 7 17 21
#> 8 8 18 NA
#> 9 9 NA 21
#> 10 10 NA NA
Created on 2019-11-11 by the reprex package (v0.3.0)
library('tidyverse')
df <- data.frame(A = seq(1, 10),
B = seq(11, 20),
C = seq(21, 30))
df %>% mutate(C = ifelse(C > 21, NA, C),
B = ifelse(C > 18, NA, B))
Hope it helps
@ mishabalyasin, Thanks for your answer, but I want the whole row to be NA for example the whole rows 2, 4, 6, 8,9, 10 which correspond to the input criterias should also marked as NA under the column A
Maybe like this.
DF<- data.frame( A= c(1:10),B=c(11:20),C=c(21,30))
library(purrr)
#> Warning: package 'purrr' was built under R version 3.5.3
SubNA <- function(A, B, C) {
if(B > 18 || C > 21) {
data.frame(A = NA, B = NA, C = NA)
} else data.frame(A = A, B= B, C=C)
}
pmap_dfr(DF, SubNA)
#> A B C
#> 1 1 11 21
#> 2 NA NA NA
#> 3 3 13 21
#> 4 NA NA NA
#> 5 5 15 21
#> 6 NA NA NA
#> 7 7 17 21
#> 8 NA NA NA
#> 9 NA NA NA
#> 10 NA NA NA
Created on 2019-11-11 by the reprex package (v0.3.0.9000)
1 Like
In that case, I'd do:
> df <- data.frame(A = seq(1, 10),
+ B = seq(11, 20),
+ C = c(21, 30))
> df
A B C
1 1 11 21
2 2 12 30
3 3 13 21
4 4 14 30
5 5 15 21
6 6 16 30
7 7 17 21
8 8 18 30
9 9 19 21
10 10 20 30
> df[which(df$C > 21), ] = NA
> df[which(df$B > 18), ] = NA
> df
A B C
1 1 11 21
2 NA NA NA
3 3 13 21
4 NA NA NA
5 5 15 21
6 NA NA NA
7 7 17 21
8 NA NA NA
9 NA NA NA
10 NA NA NA
2 Likes