If all your columns are numeric, you can use rowSums()
. Like this:
df1<- data.frame(ID = c("a", "b", "c", "d", "e"),
var1 = c(1,0 ,2 ,0 ,0 ),
var2 = c(0, 2, 0, 0, 0),
var3 = c(0,0,0,2,2),
var4 = c(0,0,NA, NA, NA))
df2$var5 <- rowSums(df1[,2:5], na.rm = TRUE)
df2
# ID var1 var2 var3 var4 var5
# 1 a 1 0 0 0 1
# 2 b 0 2 0 0 2
# 3 c 2 0 0 NA 2
# 4 d 0 0 2 NA 2
# 5 e 0 0 2 NA 2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…