Home > Enterprise >  R: trying to omit missing values before plotting
R: trying to omit missing values before plotting

Time:12-29

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

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!

CodePudding user response:

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

CodePudding user response:

You can use:

`d <- Data %>% na.omit

density(d$item2)`.

  • Related