How to replace NA with cero in a columns, if the columns beside have a values? using R

Viewed 39

I want to know a way to replace the NA of a column if the columns beside have a value, this because, using a example if the worker have values in the other columns mean he went to work that day so if he have an NA it means that should be replaced with cero, and if there are no values in the columns surrounding means he didnt go to work that day and the NA is correct

I have been doing this by sorting the other columns but its so time consuming

A sample of my data called df, the real one have 30 columns and like 30,000 rows

  df <- data.frame(
  hours = c(NA, 3, NA, 8), 
  interactions = c(NA, 3, 9, 9),
  sales = c(1, 1, 1, NA)
)
2 Answers
df$hours2 <- ifelse(
  test = is.na(df$hours) & any(!is.na(df[,c("interactions", "sales")])),
  yes = 0, 
  no = df$hours)

df
  hours interactions sales hours2
1    NA           NA     1      0
2     3            3     1      3
3    NA            9     1      0
4     8            9    NA      8

You could also do as follows:

library(dplyr)

mutate(df, X = if_else(is.na(hours) | is.na(interactions), 0, hours))

#   hours interactions sales X
# 1    NA           NA     1 0
# 2     3            3     1 3
# 3    NA            9     1 0
# 4     8            9    NA 8
Related