Veraaa Veraaa - 1 month ago 9
R Question

Transform zeros of x number of rows in NA in R

In my data frame I have only zeros up until row 1500 in the column nr.flights, that I want to transform to NA's (I have no data available about the nr.flights for the first 1500 rows). There are other values from row 1500 onwards that are zero but that needs to remain zero.

My dataframe looks like this:

Date AD Runway MTOW nr.flights
2008-01-01 A 18 376 0
2008-01-01 A 18 376 0
2008-01-01 D 36 190 0
2008-01-02 D 09 150 2
2008-01-02 A 36 280 1
2008-01-02 A 36 280 1


And I want it to look like this:

Date AD Runway MTOW nr.flights
2008-01-01 A 18 376 NA
2008-01-01 A 18 376 NA
2008-01-01 D 36 190 NA
2008-01-02 D 09 150 2
2008-01-02 A 36 280 1
2008-01-02 A 36 280 1


So far I've only managed to change the entire column into either NA's or zeros, but I want to have both of these in there. Any help would be much appreciated!

To reproduce:

df <- data.frame(Date=c("2008-01-01","2008-01-01","2008-01-01","2008-01- 02","2008-01-02","2008-01-02"),
AD = c("A", "A", "D", "D", "A", "A"), Runway = c(18, 18, 36, 09, 36,36),
MTOW = c(376, 376, 190, 150, 280, 280), nr.flights = c(0,0,0,2,1,1))

Answer

Here's a way:

is.na(df$nr.flights[1:1500])[df$nr.flights[1:1500] == 0] <- TRUE

It works by isolating the values equal to 0, then assign the NA status to TRUE. This is typically the safer option compared to df[mysubset] <- NA.

df
        Date AD Runway MTOW nr.flights
1 2008-01-01  A     18  376         NA
2 2008-01-01  A     18  376         NA
3 2008-01-01  D     36  190         NA
4 2008-01-02  D      9  150          2
5 2008-01-02  A     36  280          1
6 2008-01-02  A     36  280          1