根据标准选择观察结果

问题描述 投票:0回答:1

我有一个包含观察值(行)和变量(列)的数据框。我现在想要创建满足特定标准的观察子集。相关变量均以“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)

r subset criteria inclusion
1个回答
0
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.