0

I have a df1:

ID  Number
3   9
4   10
2   3
1   NA
8   5
6   4
9   NA

I would like to change the NAs to 1's, like below.

ID  Number
3   9
4   10
2   3
1   1
8   5
6   4
9   1
Evan
  • 1,477
  • 1
  • 17
  • 34

1 Answers1

1

With base R

df$Number[is.na(df$Number)] <- 1

Or with dplyr

library(dplyr)

df %>% 
    mutate(Number = ifelse(is.na(Number), 1, Number))

Or with data.table:

library(data.table)

setnafill(df, cols="Number", fill=1)

Output

  ID Number
1  3      9
2  4     10
3  2      3
4  1      1
5  8      5
6  6      4
7  9      1

Data

df <- structure(list(ID = c(3L, 4L, 2L, 1L, 8L, 6L, 9L), Number = c(9L, 
10L, 3L, NA, 5L, 4L, NA)), class = "data.frame", row.names = c(NA, 
-7L))
AndrewGB
  • 16,126
  • 5
  • 18
  • 49