The function below takes your input (x) and confront it to a correct vector. You can set the argument order to TRUE if the order in the input vector matters. See the 4 examples below:
# 4 dummy vectors to test the function
v1 <- c(3, 4, 6, 8, 10, 12)
v2 <- c(2, 5, 6, 8, 10, 12)
v3 <- c(2, 4, 6, 8, 10, 12)
v4 <- c(4, 2, 6, 8, 10, 12)# A 4th example where the order is reversed
# Write a function. You can edit what "correct" looks like.
# x is your object, and order is a logical argument.
# When order = FALSE (default), what counts is that all the values in your vector are in the "correct" vector.
# When order = TRUE, the order must be respected too.
check <- function(x, order = FALSE) {
correct <- seq(2, 12, by = 2)
if(!order) {
return(length((x %in% correct)[(x %in% correct)]))
} else {
return(length(which(c(order(v4) - order(correct)) == 0)))
}
}
check(v1) # [5]
check(v2) # [5]
check(v3) # [6]
check(v4) # [6]
check(v4, order = TRUE) # [4]
If your vectors are rows of a dataframe:
# Your dataframe
df <- data.frame(t(matrix(c(v1, v2, v3, v4), ncol = v4,
dimnames = list(c("first", "second", "third", "fourth", "fith", "sixth"), c("v1", "v2", "v3", "v4")))))
# Apply the function check() on every rows:
df$score <- apply(df, 1, function(x) check(x))
df$score_order <- apply(df, 1, function(x) check(x, order = TRUE))
Which in turns
df
# first second third fourth fith sixth score score_order
# v1 2 5 6 8 10 12 5 4
# v2 2 5 6 8 10 12 5 4
# v3 4 2 6 8 10 12 6 4
# v4 4 2 6 8 10 12 6 4