简体   繁体   中英

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!

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)

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