Kain_F
Kain_F

Reputation: 3

Is there an R function like fill for filling NA's with characters as const

I have a data.table as such:

missings_table = data.table( name = c("Jim","Paul",NA,"Sam"),
                         midterm = c(0,15,13,12),
                         final = c(0,NA,16,13));missings_table

What i want to do is similar to

nafill(missings_table$final,type = "const", fill = 0)

But if i try

nafill(missings_table$name,type = "const", fill = "name")

I get

'x' argument must be numeric type, or list/data.table of numeric types

Thanks :)

Upvotes: 0

Views: 1024

Answers (3)

d3hero23
d3hero23

Reputation: 392

You can use the base function is.na() works well for this and is the easiest solution.

missings_table$name[is.na(missings_table$name)] <- "name"

Upvotes: 0

Uwe
Uwe

Reputation: 42564

Unfortunately, the nafill() function currently does not support character data types.

So, here is a approach for replacing NAs in a character column by a constant value:

missings_table[is.na(name), name := "name"]
   name midterm final
1:  Jim       0     0
2: Paul      15    NA
3: name      13    16
4:  Sam      12    13

Upvotes: 5

Onyambu
Onyambu

Reputation: 79298

Since the type of your fill is constant, you could use tidyr::replace_na

tidyr::replace_na(missings_table, list(name='name', final = 0))
   name midterm final
1:  Jim       0     0
2: Paul      15     0
3: name      13    16
4:  Sam      12    13

Upvotes: 1

Related Questions