Kishan Jangam
Kishan Jangam

Reputation: 39

How can I do conditional replacement in R?

This is a simple conditional problem in R.
here is a sample data frame. The "" represents blank spaces

>df  
    A   B  
    1   Y  
    1   N  
    ""  Y  
    0   N  
    ""  N  
    1   Y  
    0   Y  
    ""  N  
    0   Y

I am trying to check IF df$B == "Y" then Print 1 in df$A at blank spaces.

I have tried df$A[df$A == ""] <- df$B[df$B == "Y"]
this changes all the blank spaces in to "Y".

Please help!

Upvotes: 0

Views: 414

Answers (1)

Ian
Ian

Reputation: 451

Is this what you are after?

library("dplyr")
library("tibble")

df <- 
tibble::tribble(
  ~A,   ~B,
  1,  "Y",
  1,  "N",
  "",  "Y",
  0,  "N",
  "",  "N",
  1,  "Y",
  0,  "Y",
  "",  "N",
  0,  "Y")

df %>% mutate(A = ifelse(B == "Y" & A == "",1,A))
#> # A tibble: 9 x 2
#>       A     B
#>   <chr> <chr>
#> 1     1     Y
#> 2     1     N
#> 3     1     Y
#> 4     0     N
#> 5           N
#> 6     1     Y
#> 7     0     Y
#> 8           N
#> 9     0     Y

And here's a base version:

df$A <- ifelse(df$B == "Y" & df$A == "",1,df$A)

Upvotes: 1

Related Questions