0

I'm trying to create a new variable that contains the substitution of where "NA" is in the Var1 variable by 0 and leave the other observations as they normally are, using a mutate function from the dplyr package. However, I am not getting what I wanted.

Below are the data and codes:

Dados1 <- data.frame(Var1 = c(rep("NA", 4), "H", "Q",rep("NA", 4)))
Dados1
library(dplyr)

Dados1 <- Dados1 %>% 
  dplyr::mutate(NewCode = ifelse(Var1 == "NA", "0"))
Dados1

Erro: Problem with `mutate()` input `NewCode`.
x argumento "no" ausente, sem padrĂ£o
i Input `NewCode` is `ifelse(Var1 == "NA", "0")`.
Run `rlang::last_error()` to see where the error occurred.
> Dados1
user55546
  • 37
  • 1
  • 15

2 Answers2

1

Try this:

library(dplyr)
#Code
Dados1 <- Dados1 %>% dplyr::mutate(NewCode = ifelse(Var1=='NA', "0",Var1))    

Output:

Dados1
   Var1 NewCode
1    NA       0
2    NA       0
3    NA       0
4    NA       0
5     H       H
6     Q       Q
7    NA       0
8    NA       0
9    NA       0
10   NA       0

Also for leading with real NA you can try this:

#Data 2
Dados1 <- data.frame(Var1 = c(rep(NA, 4), "H", "Q",rep(NA, 4)),stringsAsFactors = F)
#Code 2
Dados1 <- Dados1 %>% 
  dplyr::mutate(NewCode = ifelse(is.na(Var1), "0",Var1))

Output:

Dados1
   Var1 NewCode
1  <NA>       0
2  <NA>       0
3  <NA>       0
4  <NA>       0
5     H       H
6     Q       Q
7  <NA>       0
8  <NA>       0
9  <NA>       0
10 <NA>       0
Duck
  • 39,058
  • 13
  • 42
  • 84
0

Your syntax is wrong: when using ifelse (or the dplyr version if_else) you have to provide three inputs.

  1. A logical statement
  2. An output in case the statement is met
  3. An output in case the statement is not met.

Number 3 is missing in your case.

Dados1 <- Dados1 %>% 
  dplyr::mutate(NewCode = ifelse(Var1 == "NA", "0", VaR1))
Cettt
  • 11,460
  • 7
  • 35
  • 58