I have this huge matrix of data with columns for year, month, day and precipitation which I need to order and also delete the row when the precipitation is NA (which happens on the day 31 of every month that only has 30 days and Februaries...). After consulting the r help files I used the following code:
dat<- aa[order(aa$year, aa$month, aa$day, na.last=NA),]
It ordered my data perfectly but I still have all the NAs... Can anyone tell me why it hasn't work?
thanks
> head(dat)
code year month station ALTITUD PROV LONGITUD LATITUD day P1 id
1.1 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 1 0 1
1.2 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 2 0 1
1.3 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 3 0 1
1.4 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 4 0 1
1.5 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 5 0 1
1.6 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 6 0 1
To remove all rows having NA, we can use na. omit function. For Example, if we have a data frame called df that contains some NA values then we can remove all rows that contains at least one NA by using the command na. omit(df).
Method 1: Using is.na() We can remove those NA values from the vector by using is.na(). is.na() is used to get the na values based on the vector index. ! is.na() will get the values except na.
To remove observations with missing values in at least one column, you can use the na. omit() function. The na. omit() function in the R language inspects all columns from a data frame and drops rows that have NA's in one or more columns.
The na. omit() function returns a list without any rows that contain na values. It will drop rows with na value / nan values. This is the fastest way to remove na rows in the R programming language.
The na.last
argument to order
only removes NA
from the objects passed to order
via ...
. Your NA
are in aa$precipitation
, not aa$year
, aa$month
, or aa$day
, so you need:
dat <- na.omit(aa[order(aa$year, aa$month, aa$day),])
You may want to consider using a time-series class like zoo or xts for time-series data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With