0

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
  • 29
  • 5

3 Answers3

3

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
  • 874,273
  • 37
  • 540
  • 662
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
  • 72,363
  • 6
  • 19
  • 66
  • 1
    This replaces all blanks, ignoring OP's requirement that this should happen on rows *"if Variable A == 0"*. And if you want to replace blanks, using `== ""` will be more efficient than regex. – Gregor Thomas May 05 '21 at 15:39
  • Thanks Gregor Thomas. I have updated. – TarJae May 05 '21 at 16:21
  • @TarJae I used the code `df$Variable.B <- sub("^$", "0", df$Variable.B)` and `df$Variable.C <- sub("^$", "0", df$Variable.C)` and it works but I still don't understand why it works. Would someone be able to explain what this code is doing? Thank you again! – Tyler May 05 '21 at 18:31
1
rows_to_replace <- df$Variable.A == 0
df[rows_to_replace, c("Variable.B", "Variable.C")] <- 0
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294