In R, I am trying to generate a column of normally distributed random values based on columns existing in the dataframe. As there are NAs in the columns I am using, NAs are returned in the new column. Is there a way I can ignore these NAs?
I've used the built-in "airquality" data set as a dummy example to illustrate my problem as it includes NAs.
Example Code:
> airquality$random <- rnorm(n = nrow(airquality), mean = (50 + airquality$Ozone*1.2 + airquality$Solar.R*0.5 + airquality$Wind*3 + airquality$Temp*0.2), sd = 5)
Warning message:
In rnorm(n = nrow(airquality), mean = (50 + airquality$Ozone * 1.2 + :
NAs produced
> head(airquality)
Ozone Solar.R Wind Temp Month Day random
1 41 190 7.4 67 5 1 222.5487
2 36 118 8.0 72 5 2 191.8911
3 12 149 12.6 74 5 3 188.5913
4 18 313 11.5 62 5 4 273.7623
5 NA NA 14.3 56 5 5 NaN
6 28 NA 14.9 66 5 6 NaN
Rows 5 and 6 have NaN listed in the "random" column. I would like the "NA" values to be ignored (NAs could be in any column), so that row 5 would have a value of 100.22697*, and row 6 would have a value of 143.1274*
*these values were obtained by manually removing the NA columns from the code, but this isn't practical if I have a data set of thousands of rows and tens of columns.
Including na.rm = TRUE within the mean = () section returns an error message:
> airquality$random <- rnorm(n = nrow(airquality), mean = (50 + airquality$Ozone*1.2 + airquality$Solar.R*0.5 + airquality$Wind*3 + airquality$Temp*0.2, na.rm = TRUE), sd = 5)
Error: unexpected ',' in "airquality$random <- rnorm(n = nrow(airquality), mean = (50 + airquality$Ozone*1.2 + airquality$Solar.R*0.5 + airquality$Wind*3 + airquality$Temp*0.2,"
If I put na.rm = TRUE at the end of the rnorm() section instead, it returns a different error message:
> airquality$random <- rnorm(n = nrow(airquality), mean = (50 + airquality$Ozone*1.2 + airquality$Solar.R*0.5 + airquality$Wind*3 + airquality$Temp*0.2), sd = 5, na.rm = TRUE)
Error in rnorm(n = nrow(airquality), mean = (50 + airquality$Ozone * 1.2 + :
unused argument (na.rm = TRUE)