Reputation: 119
Consider a vector x:
x <- c(0, 5, 10, 25, 30)
I would like to create a new vector with "missing values," which means all the values that were "skipped" if I were to have a sequence with intervals of 5.
So for this example, the output shouldbe:
xna <- c(15, 20)
Additionally, I would have to make a function so that I can do this to any vector x.
nats <- function(x){
lastvalue <- x[length(x)]
firstvalue <-x[1]
xseq <- seq(firstvalue, lastvalue, 5)
for i in xseq {
# if x is not in x seq put it into a vecotr xna #
}
xna
}
I really have no idea how to do this. Would really appreciate suggestions or if there is already a function that can do this.
Please help,
Upvotes: 0
Views: 62
Reputation: 12107
Using %in%
operator. See https://stat.ethz.ch/R-manual/R-devel/library/base/html/match.html
xna <- xseq[!xseq%in%x]
Upvotes: 0
Reputation: 389275
If you need as a function,
nats <- function(x, interval){
lastvalue <- x[length(x)]
firstvalue <-x[1]
xseq <- seq(firstvalue, lastvalue, interval)
xna <- xseq[!xseq %in% x]
return(xna)
}
x <- c(0,5,10, 15,25,30)
nats(x, 5)
#[1] 20
x <- c(3, 6,18)
nats(x, 3)
#[1] 9 12 15
Upvotes: 3
Reputation: 50738
Solution in base R (see ?setdiff
)
# Your data
x <- c(0, 5, 10, 25, 30)
# Your sequence
y <- seq(0, max(x), by = 5);
# "Skipped" values
s <- setdiff(y, x);
print(s);
[1] 15 20
Upvotes: 1