根据条件过滤数据

时间:2019-10-18 12:35:30

标签: r filter dplyr

我有以下数据框:

mydata <- data.frame(Farmer = c(1,2,3,4,5,6,7,8),
              Farmer_Year = seq(2009,2016,1),
              Total_Output = c(560,290,458,612,450,380,500,290),
              Vegetable_Out = c(354,120,330,260,380,2020,357,95))

我只选择蔬菜产量超过总产量60%的农民。我该如何使用R?

4 个答案:

答案 0 :(得分:1)

我相信使用dplyr包可以做到这一点。

library(dplyr)

mydata %>% 
  filter(`Vegetable Out` / `Total output` > 0.6)

将来,请阅读如何通过在R中直接可用的形式共享数据来创建minimal reproductible example,以便更轻松地为您提供帮助。

另外,读取dplyr documentation很有用,因为子集是对数据帧的非常基本的操作。

答案 1 :(得分:1)

您可以尝试以下 ARRAY公式:CTRL + SHIFT + ENTER

=IFERROR(INDEX($A$1:$D$11,SMALL(IF($D$2:$D$11/$C$2:$C$11>0.6,ROW($A$2:$A$11)-1),ROW(A2)),COLUMN(A1)),"")

enter image description here

更新:

此帖子以前被标记为EXCEL-Formula

答案 2 :(得分:0)

使用data.table软件包

library(data.table)
setDT(dt)
dt[, .SD[`Vegetable Out` / `Total output` > 0.6]]

答案 3 :(得分:0)

请提供代码以重现上面的示例。 这是不加载任何库的基本代码

Farmer <-  c(1, 2, 3, 4, 5, 6, 7, 8)

year <-  c(2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016)

`Total output` <- c(560, 290, 458, 612, 445, 380, 500, 290)

`Vegetable Out` <- c(334, 120, 330, 260, 380, 200, 357, 95)
df <- data.frame(Farmer, year, `Total output`, `Vegetable Out`)

df[df$Vegetable.Out / df$Total.output >= 0.6, ]

结果

  Farmer year Total.output Vegetable.Out
3      3 2011          458           330
5      5 2013          445           380
7      7 2015          500           357