【问题标题】:Subset of data based on conditions [closed]基于条件的数据子集[关闭]
【发布时间】:2015-08-21 08:30:05
【问题描述】:

我研究了该网站,但发现没有 100% 回答问题的回复。我有一个data_frame 的 50 个变量的 258 个观察值(在此处采样):

pdis_reel   distance    corde   date_course spe ssp code_hippo  libel_hippo
3000    3000    G   25/03/15    T   A   1303    Marseille-Borély
2625    2625    D   18/03/15    T   A   4701    Agen
2950    2925    G   17/02/15    T   A   601 Cagnes-sur-Mer
2675    2650    G   19/01/15    T   A   1302    Marseille-Vivaux
2650    2650    G   29/11/14    T   A   1302    Marseille-Vivaux
3250    3225    D   09/11/14    T   A   4203    Saint-Galmier
3025    3000    G   29/10/14    T   A   1303    Marseille-Borély
2625    2600    D   04/10/14    T   A   303 Moulins
2875    2850    G   28/09/14    T   A   6901    Lyon-Parilly
2600    2600    D   10/09/14    T   A   8404    Cavaillon
4175    4150    D   06/09/14    T   A   7513    Vichy
2675    2675    G   17/08/14    T   A   102 Divonne-les-Bains
2700    2700    D   03/08/14    T   A   7301    Aix-les-Bains
2875    2850    G   04/07/14    T   A   4201    Feurs
2300    2300    G   21/05/14    T   A   1303    Marseille-Borély
2650    2650    D   03/05/14    T   A   8301    Hyères
2650    2650    D   27/04/14    T   A   401 Oraison
2850    2850    G   22/04/14    T   A   6901    Lyon-Parilly

我想提取最接近匹配条件的所有行,例如:

centpoourcent<- subset(data_frame, corde=="D" & pdis_reel==2900+-200)

当我查看 centpourcent 时,它有 258 行和 0 列,为什么?

另外,我不清楚为什么不建议在脚本或程序中使用subset()

【问题讨论】:

  • 你的条件是corde=="D" &amp; pdis_reel &gt; 2700 &amp; pdis_reel &lt; 3100吗?
  • 对,但我仍然得到 centpourcent 的“0 列 258 行的数据框”...
  • 那么您的数据中没有任何行符合该条件。就如此容易。除非您正在寻找 OR 语句,例如 subset(data_frame, corde=="D" | (pdis_reel &gt; 2700 &amp; pdis_reel &lt; 3100)) 也许?
  • 抱歉拼写错误。谢谢。
  • 这不是错字,而是没有正确理解 R 语法 IMO

标签: r conditional-statements subset


【解决方案1】:

(根据要求)我将尝试解释一下您的代码有什么问题。

当做像 2900+-200 这样的事情时,你基本上是在告诉 R

  1. 从 LHS 获取号码
  2. 将其添加到RHS号码上的号码的减号

换句话说:2900 - 200 = 2700。这不是在R中指定范围的方法

考虑以下示例数据

set.seed(123)
test <- sample(150, 20, replace  = TRUE) 

假设我们的条件是 test == 60+-20

我们都可以

test[test >= 40 & test <= 80]
## [1] 44 62 80 69 69 50

或者

between <- function(x, upper, lower) x[x >= upper & x <= lower]
between(test, 40, 80)
## [1] 44 62 80 69 69 50

或者

'%between%' <- function(x, y) x[x >= y[1] & x <= y[2]]
test %between% c(40, 80)
## [1] 44 62 80 69 69 50

或者只加载具有相同功能的dplyrdata.table

【讨论】:

  • 谢谢大卫,我最喜欢函数版本,因为它们看起来更灵活使用。接下来我会尝试在约会时参加比赛。我想获取记录集的最新日期 (max()),从中减去 45 天 (-45) 并过滤我的数据框,仅保留该范围内的行。
猜你喜欢
  • 2020-10-23
  • 1970-01-01
  • 2018-12-06
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多