Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Column in dataframe turns from integer to numeric when replacing NA with 0

In a dataframe, when I replace NA with 0 using obt[is.na(obt)] <- 0, the column type changes from integer to numeric.

str(obt)
 ...
 $ Units: int  NA NA 2 1 NA NA NA 1 NA NA ...

obt[is.na(obt)] <- 0

str(obt)
 ...
 $ Units: num  0 0 2 1 0 0 0 1 0 0 ...

How can I avoid that?


Sample data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

obt <- structure(list(Date = structure(c(19677, 19678, 19679, 19680, 
19681, 19682, 19683, 19684, 19685, 19686), class = "Date"), Title = structure(c(NA, 
NA, 3L, 3L, NA, NA, NA, 3L, NA, NA), levels = c("A", "D", "L", 
"C"), class = "factor"), Units = c(NA, NA, 2L, 1L, NA, NA, NA, 
1L, NA, NA)), row.names = c(NA, 10L), class = "data.frame")

>Solution :

Using L to indicate the number is an integer (same as using as.integer(0)).

obt$Units[is.na(obt$Units)] <- 0L

class(obt$Units)
[1] "integer"

Another example, when using dput

dput(as.integer(0))
0L

dput(as.numeric(0))
0

# R is using numeric when not explicitly stated (exceptions are e.g. sequences)
dput(0)
0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading