# Get the index of columns starting with "X"
index <- which(substr(colnames(df), 1, 1) == "X")
# Compute the new variables based on your conditions
df$Num_Low <- rowSums(df[, index] < 1 &
df[, index] > 0)
df$Num_0 <- rowSums(df[, index] == 0)
df
# name X1 X2 X3 Num_Low Num_0
#1 name1 0.2 0.5 1 2 0
#2 name2 1.0 1.0 1 0 0
#3 name3 0.2 0.2 0 2 1
#4 name4 0.5 1.0 1 1 0
#5 name5 0.0 0.0 1 0 2
#6 name6 0.2 0.0 0 1 2
dplyr
версия:
library(dplyr)
df %>%
select(index) %>%
mutate(Num_Low = rowSums(. < 1 & . > 0),
Num_0 = rowSums(. == 0))
# name X1 X2 X3 Num_Low Num_0
#1 name1 0.2 0.5 1 2 0
#2 name2 1.0 1.0 1 0 0
#3 name3 0.2 0.2 0 2 1
#4 name4 0.5 1.0 1 1 0
#5 name5 0.0 0.0 1 0 2
#6 name6 0.2 0.0 0 1 2
Пример данных
df <- data.frame(name = paste0("name", 1:6),
X1 = c(0.2,1,0.2,0.5,0,0.2),
X2 = c(0.5,1,0.2,1,0,0),
X3 = c(1,1,0,1,1,0))