我有一个包含观察值(行)和变量(列)的数据框。我现在想要创建满足特定标准的观察子集。相关变量均以“incl_”开头,编号从1到5,如果满足则等于1(例如“incl_1” = 1)。
是否有更有效的方法来执行以下操作:
红帽子<- df[df$incl_1 == 1 &df$incl_2 == 1 & df$incl_3 == 1 & df$incl_4 == 1 & df$incl_5,]
我尝试了这个,这显然不起作用,但可能会让你了解我正在尝试做什么:
df2<- filter(df, select(df, startswith("incl")) ==1)
library(tidyverse)
# identify the columns of interest
(nms <- names(iris)[startsWith(
names(iris),
"Sepal"
)])
(rows_to_keep <- mutate(iris, across(
nms,
\(x) between(x, 3, 5) #some rule that all the columns of interest should satisfy like ==1 or between 3 and 5
),
rowid = row_number()
) |>
rowwise() |>
mutate(
ptest = all(!!!syms(nms))
) |> filter(ptest) |> select(rowid))
# do the filter
iris |> mutate(rowid = row_number()) |>
inner_join(rows_to_keep) |> select(-rowid)