2021年3月6日星期六

Replace NA with modified version of previous number in R vector

I have a vector with some NAs, and I want to replace some of those NAs with the previous non-NA value minus 0.1. I also don't want to replace NAs if the string of NAs is longer than a certain length (e.g., 2). Here's an example

x <- c(1:3, NA, 4, NA, NA, 5, NA, NA, NA, 6, NA)  

I want to make a vector that looks like

x_prime <- c(1:3, 2.9, 4, 3.9, 3.8, 5, NA, NA, NA, 6, NA)  

Printing this out looks like:

> x_prime   [1] 1.0 2.0 3.0 2.9 4.0 3.9 3.8 5.0  NA  NA  NA 6.0  NA  

As an added complication, I want to keep track of the indices that I modified, so I also want a vector that looks like

idx <- c(4, 6,7, 13)  

I have found some similar questions on SO like this, and I've tried similar functions to those presented there, but haven't had success. Any ideas? Thank you in advance.

https://stackoverflow.com/questions/66499308/replace-na-with-modified-version-of-previous-number-in-r-vector March 06, 2021 at 04:35AM

没有评论:

发表评论