I work on survey data and build indexes by combining answers from different questions.
I want to create a new variable scoring the average of answers to 3 questions (which are on a 1 to 10 scale) when answers are minimum 2. Else I want my newvar to score 0. All this under the condition that answer are all different from NA.
Here is an example of what i try to obtain
DF <-
data.frame(matrix(
c(1, 3, 4, 9, 4, 3, 10, 4, 6, 4, 7, NA),
nrow = 4,
ncol = 3
))
# X1 X2 X3
# 1 1 4 6
# 2 3 3 4
# 3 4 10 7
# 4 9 4 NA
I would like to create DF$new_var_ave such as
# X1 X2 X3 new_var_ave
# 1 1 4 6 0
# 2 3 3 4 3.3
# 3 4 10 7 7
# 4 9 4 NA NA
I have tried :
```R
DF$new_var_ave <-
apply(DB_W[, c("X1", "X2", "X3")], 1, function(x) {
ifelse(any(is.na(x)), NA, ifelse(all(x > 2), mean, 0))})`
However it fails and I received error text:
Error in rep(yes, length.out = len) :
attempt to replicate an object of type 'closure'
Thanks a lot for your help and suggestion.