2021年4月28日星期三

How can I make some row values NA if other is NA in R?

I have a dataframe with three columns Time, observed value (Obs.Value), and an interpolated value (Interp.Value). If the value of Obs.Value is NA then the value of Interp.Value should also be NA. I can make the whole row NA but I need to keep the Time value.

Here is the repex:

dat <- data.frame(matrix(ncol = 3, nrow = 10))  x <- c("Time", "Obs.Value", "Interp.Value")  colnames(dat) <- x  dat$Time <- seq(1,10,1)  dat$Obs.Value <- c(5,6,7,NA,NA,5,4,3,NA,2)  interp <- approx(dat$Time,dat$Obs.Value,dat$Time)  dat$Interp.Value <- round(interp$y,1)  

Here is the code that makes the whole row NA

dat[with(dat, is.na(Obs.Value)|is.na("Interp.Value")),] <- NA  

Here is what the output should look like:

   Time Obs.Value Interp.Value  1     1         5            5  2     2         6            6  3     3         7            7  4     4        NA           NA  5     5        NA           NA  6     6         5            5  7     7         4            4  8     8         3            3  9     9        NA           NA  10   10         2            2  
https://stackoverflow.com/questions/67309727/how-can-i-make-some-row-values-na-if-other-is-na-in-r April 29, 2021 at 09:01AM

没有评论:

发表评论