-1

This is an example of my data

df = data.frame(id = rep(1:3, each = 1), 
                test = sample(40:100, 3), 
                Sets = c(NA,4,4),
                CheWt = c(NA,4,NA),
                LatWt = c(NA,5,5))

I'd like to turn all the NA to 0 in columns which have "Wt" in the header. I am trying to use dplyr and mutate across

df = df%>%
  mutate(across(contains("Wt"), replace(is.na(), 0)))

This is the error

Error: Problem with `mutate()` input `..1`.
x argument "values" is missing, with no default
i Input `..1` is `(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...`.
Mark Davies
  • 787
  • 5
  • 18
  • 2
    `replace()` takes 3 args and you were only passing it 2. `mutate(across(contains("Wt"), ~ replace(., is.na(.), 0)))` – Nate Mar 08 '21 at 15:50
  • `df[grep("Wt", names(df))][is.na(df[grep("Wt", names(df))])] <- 0` – jay.sf Mar 08 '21 at 16:31

2 Answers2

3

replace needs 3 arguments: the value, the index of values to replace, and the replacement. And you need to use ~ for purrr-style anonymous functions:

df = df %>%
  mutate(across(contains("Wt"), ~replace(., is.na(.), 0)))
df
#   id test Sets CheWt LatWt
# 1  1   93   NA     0     0
# 2  2   44    4     4     5
# 3  3   80    4     0     5

Or you can use replace_na for a somewhat simpler interface:

df = df%>%
  mutate(across(contains("Wt"), replace_na, 0))
df
#   id test Sets CheWt LatWt
# 1  1   73   NA     0     0
# 2  2   43    4     4     5
# 3  3   54    4     0     5
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

Here is a solution using ifelse and is.na.


library(dplyr)


df = data.frame(id = rep(1:3, each = 1), 
                test = sample(40:100, 3), 
                Sets = c(NA,4,4),
                CheWt = c(NA,4,NA),
                LatWt = c(NA,5,5))


df = mutate(df, across(contains("Wt"), ~ifelse(is.na(.x), 0, .x)))


#>   id test Sets CheWt LatWt
#> 1  1   97   NA     0     0
#> 2  2   79    4     4     5
#> 3  3   75    4     0     5

Created on 2021-03-08 by the reprex package (v0.3.0)

Eric
  • 2,699
  • 5
  • 17