【问题标题】:Subset a data frame on two conditions exclusively for each row专门为每一行在两个条件下对数据框进行子集
【发布时间】:2020-08-26 09:38:36
【问题描述】:

我有一个数据框,我想从中提取一列中具有特定值并在另一列中具有另一个特定值的行。我想像下面的代码一样从 df 转到 df_final:

x = c(25,25,25,25,44,44,44,44,44,76,76)
y = c(1,2,3,4,1,4,6,7,9,4,3)


df<- data.frame(x,y)

df1 <- df %>% filter(x == 25 & y == 2)
df2 <- df %>% filter(x == 44 & y == 6)
df3 <- df %>% filter(x == 76 & y == 3)

df_final <- rbind(df1,df2,df3)


# desired result:

print(df_final)
   x y
1 25 2
2 44 6
3 76 3

我曾尝试将过滤器与 dplyr 一起使用,但 dplyr 匹配过滤后的 x 和 y 内的所有内容,导致行数过多,如下所示:

df_final <- df %>% filter(x %in% c(25,44,76) & y %in% c(2,6,3))


# non-desired result:

print(df_final)
   x y
1 25 2
2 25 3
3 44 6
4 76 3

有没有办法专门使用 dplyr 进行匹配?过滤后的 x 中的第一个实例到过滤后的 y 中的第一个实例,过滤后的 x 中的第二个实例到过滤后的 y 中的第二个实例等等......(当然,除了 dplyr 之外的其他包也可以)

【问题讨论】:

  • 您可以使用df %&gt;% filter(x == 25 &amp; y == 2 | x == 44 &amp; y == 6 | x == 76 &amp; y == 3),但我想您正在寻找不同的方法。
  • 谢谢@Let'stry 它对我的数据来说有点太长了,我不能全部硬编码,但我明白你背后的逻辑! :)

标签: r dataframe dplyr subset


【解决方案1】:

你可以做1个条件,然后使用evalparse

x_cond <- c(25, 44, 76)
y_cond <- c(2, 6, 3)
final_cond <- map2_chr(x_cond, y_cond, ~str_c("x == ", .x, " & y == ", .y)) %>%
  str_c(collapse = " | ")
df %>% filter(eval(parse(text = final_cond)))

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 2022-06-18
    • 2022-01-09
    • 2020-04-15
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多