Reputation: 59
Here's an example of how my data looks like:
pupilsize <- c(500, 400, NA, NA, 100, 600, 500, NA, NA, NA, 500)
rlelength <- c(4,4,2,2,6,6,6,90,90,90,50)
data <- data.frame(cbind(pupilsize,rlelength))
I would like to apply the na.approx function to the chunk of NA value in data$pupilsize only if the number in data$rlelength is smaller than 86.
The end result should be
data$pupilsize
[1] 500 400 300 200 100 600 500 NA NA NA 500
I am having a lot of trouble segmenting the chunk that of NA values I want. Any help is greatly appreciated!
Upvotes: 1
Views: 53
Reputation: 887118
We can use ifelse
data$pupilsize <- with(data, ifelse(rlelength< 86, na.approx(pupilsize), pupilsize))
data$pupilsize
#[1] 500 400 300 200 100 600 500 NA NA NA 500
Or
i1 <- data$rlelength < 86
data$pupilsize[i1] <- na.approx(data$pupilsize[i1])
Or we can use data.table
methods for efficiency.
library(data.table)
setDT(data)[rlelength < 86, pupilsize := na.approx(pupilsize)]
Upvotes: 2