-1

I want to replace some empty cells in Variable B and Variable C with 0 if Variable A == 0. If Variable A equals anything but 0 I would like Variable B and Variable C to stay the same. I've created a table below and I have a screenshot attached to help explain what I mean.

Variable A Variable B Variable C
0
0
1 3 8

Essentially, if Variable A == 0, I want Variable B == 0 and Variable C == 0, but if Variable A has a value then I want Variable A, Variable B, and Variable C to keep their original value.

Screenshot to help explain: https://i.stack.imgur.com/OihrX.png

Tyler
  • 17
  • 3

3 Answers3

2

Update Thanks to Gregor Thomas for drawing attention

df$Variable.B <- ifelse(df$Variable.A==0, 0,df$Variable.B)
df$Variable.C <- ifelse(df$Variable.A==0, 0,df$Variable.C)

First answer without taking into account if Variable == 0 For blank cells:

df$Variable.B <- sub("^$", "0", df$Variable.B)
df$Variable.C <- sub("^$", "0", df$Variable.C)

Output:

  Variable.A Variable.B Variable.C
       <int> <chr>      <chr>     
1          0 0          0         
2          0 0          0         
3          1 3          8  

data:

structure(list(Variable.A = c(0L, 0L, 1L), Variable.B = c("", 
"", "3"), Variable.C = c("", "", "8")), row.names = c(NA, -3L
), class = c("tbl_df", "tbl", "data.frame"))
TarJae
  • 43,365
  • 4
  • 14
  • 40
2

Using dplyr

library(dplyr)    
df <- df %>%
    mutate(across(-1,  ~ as.numeric(replace(., . == '', 0))))
       

-output

df
# A tibble: 3 x 3
#  Variable.A Variable.B Variable.C
#       <int>      <dbl>      <dbl>
#1          0          0          0
#2          0          0          0
#3          1          3          8

data

df <- structure(list(Variable.A = c(0L, 0L, 1L), Variable.B = c("", 
"", "3"), Variable.C = c("", "", "8")), row.names = c(NA, -3L
), class = c("tbl_df", "tbl", "data.frame"))
akrun
  • 789,025
  • 32
  • 460
  • 575
1
rows_to_replace <- df$Variable.A == 0
df[rows_to_replace, c("Variable.B", "Variable.C")] <- 0
Gregor Thomas
  • 119,032
  • 17
  • 152
  • 277