Search code examples
rdplyr

How to replace the dataset with one value if it satisfies a condition, if not with another value


I have a dataset with 30 columns. An example would look something like this

data <- data.frame(name=c("A", "B", "C", "D", "E", "C", "A", "B"),
                 place=c("B", "c", "F", "C", "G", "A", "H", "A"))

Now I would like to replace the whole of dataset with value of 1 if name=A and with 0 if not equal to 1.


Solution

  • If you want to replace the row of the dataset where name == 'A', you can do the follwoing,

    library(dplyr)
    
    data <- data.frame(name=c("A", "B", "C", "D", "E", "C", "A", "B"),
                       place=c("B", "c", "F", "C", "G", "A", "H", "A"))
    
    data %>% 
      mutate(
        across(.fns = ~ if_else(name == "A", 1, 0))
      )
    
    #>   name place
    #> 1    1     1
    #> 2    0     0
    #> 3    0     0
    #> 4    0     0
    #> 5    0     0
    #> 6    0     0
    #> 7    1     1
    #> 8    0     0
    

    Created on 2023-01-06 by the reprex package (v2.0.1)

    Or, if you want to replace all value of the data for 'A' with 1 or else 0 for other value,

    library(dplyr)
    
    data <- data.frame(
        name = c("A", "B", "C", "D", "E", "C", "A", "B"),
        place = c("B", "c", "F", "C", "G", "A", "H", "A")
    )
    
    data %>%
        mutate(
            across(.fns = ~ if_else(.x == "A", 1, 0))
        )
    
    #>   name place
    #> 1    1     0
    #> 2    0     0
    #> 3    0     0
    #> 4    0     0
    #> 5    0     0
    #> 6    0     1
    #> 7    1     0
    #> 8    0     1
    

    Created on 2023-01-06 by the reprex package (v2.0.1)