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

R: trying to omit missing values before plotting

Any idea why omitting N/A does not work with this code?

d <- density(Data$item2) %>%
  na.omit() 

I get the error Error in density.default(Data$item2) : 'x' contains missing values

This didn’t work either

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

d <- Data %>% na.omit() %>% 
  density(Data$item2)

My data

structure(list(item1 = c(5, 5, 5, 5, 4, 4, 2, 1, 3, 
4, 4, 3, 2, 5, 2, 4, 4, 3, 6, 5, 3, 2, 5, 3, 3, 1, 3, 5, 1, 3, 
2, 6, 3, 5, 4, 4, 3, 5, 6, 3, 2, 6, 6, 5, 2, 2, 2, 3, 3, 3), 
    item2 = c(5, 4, 5, 1, 2, 2, 3, 2, 2, 2, 2, 3, 2, 
    5, 1, 4, 4, 3, 3, 5, 3, 2, 4, 4, 3, 4, 4, 3, 7, NA, 2, 4, 
    2, 4, 2, 3, 5, 3, 5, 3, 2, 6, 6, 7, 2, 3, 2, 3, 1, 4)), row.names = c(NA, 
-50L), class = c("tbl_df", "tbl", "data.frame"))

I also tried to omit all the N/A in the beginning with this code, but it did not solve the problem

Data <- read_excel("C:/location/Data.xlsx") %>% 
  na.omit()

So, how to do this? Thanks for your help!

>Solution :

You need to remove the NA values from your data, not from the density object.

Data$item2 %>% 
  na.omit() %>% 
  density() %>%
  plot()

enter image description here

Alternatively, use the na.rm = TRUE argument in density:

Data$item2 %>% 
  density(na.rm = TRUE) %>%
  plot()

enter image description here

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