在我的数据框中,我在nr.flights列中只有零行直到第1500行,我想转换为NA'(我没有关于前1500行的nr.flights的数据) 。从第1500行开始,还有其他值为零,但需要保持为零。
我的数据框如下所示:
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
我希望它看起来像这样:
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
到目前为止,我只设法将整个列更改为NA或0或者零,但我希望在这里有两个。任何帮助将非常感激!
重现:
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))
答案 0 :(得分:2)
这是一种方式:
is.na(df$nr.flights[1:1500])[df$nr.flights[1:1500] == 0] <- TRUE
它的工作原理是将值等于0,然后将NA
状态指定给TRUE
。与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
答案 1 :(得分:0)
以下是使用data.table
library(data.table)
setDT(df)[1:.N <=1500 & !nr.flights, nr.flights := 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