In this case, I'd probably propose the following. I don't see how your average values make sense exactly as you have 1,0,1 for the first person which is 2/3 so needs to be 0.6? As you will see the below will work on your NA
case too.
library(tidyverse)
df <-
data.frame(
S.ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
Location = c(1, 1, 1, 2, 2, 2, 3, 3, 4, 4),
I1 = c(1, 0, 1, 0, 1, 0, 1, 0, 1, 0),
I2 = c(0, 1, 0, 1, 1, 0, 1, 0, 0, 1),
I3 = c(1, 0, NA, 1, 1, 1, 0, 1, 1, 0)
)
df_selected <- df %>% select(I1:I3)
average <- apply(X=df_selected, MARGIN=1, FUN=mean, na.rm=TRUE)
df_final <- cbind(df,average)
df_final
#> S.ID Location I1 I2 I3 average
#> 1 1 1 1 0 1 0.6666667
#> 2 2 1 0 1 0 0.3333333
#> 3 3 1 1 0 NA 0.5000000
#> 4 4 2 0 1 1 0.6666667
#> 5 5 2 1 1 1 1.0000000
#> 6 6 2 0 0 1 0.3333333
#> 7 7 3 1 1 0 0.6666667
#> 8 8 3 0 0 1 0.3333333
#> 9 9 4 1 0 1 0.6666667
#> 10 10 4 0 1 0 0.3333333
Created on 2020-10-22 by the reprex package (v0.3.0)