【问题标题】:Subset data in r that includes group_by functionr 中包含 group_by 函数的子集数据
【发布时间】:2017-11-07 22:54:39
【问题描述】:

这是对以下问题的后续问题给here

我有以下数据

数据:

df = structure(list(Org_ID = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L), 
    Market_volume = c(100L, 200L, 300L, 50L, 500L, 400L, 200L, 
    300L, 100L), Indicator_variable = c(1L, 0L, 0L, 1L, 1L, 0L, 
    0L, 0L, 0L),variable3=c(10L, 1L, 1L, 4L, 2L, 3L, 3L, 10L, 3L),variable4=c(2L, 1L, 1L, 7L, 2L, 3L, 3L, 8L, 3L)).Names = c("Org_ID", "Market_volume", "Indicator_variable","Var3","Var4"
), class = "data.frame", row.names = c(NA, -9L))

使用 (dplyr),我通过以下函数按 Org_ID 计算了 NA 按市场交易量计算的百分比

df %>%
  group_by(Org_ID) %>%
  summarize(sum_market_vol = sum(Market_volume*!Indicator_variable),
            tot_market_vol = sum(Market_volume)) %>%
  transmute(Org_ID, Perc_Market_Vol = 100*sum_market_vol/tot_market_vol)

结果:

# A tibble: 3 x 2
  Org_ID Perc_Market_Vol
   <int>           <dbl>
1      1        83.33333
2      2         0.00000
3      3       100.00000

问题: 我想通过删除 Org_ID 的所有行(比如 2)# X if perc_market_vol

我希望新数据如下所示:

df1 = structure(list(Org_ID = c(1L, 1L, 1L, 3L, 3L, 3L, 3L), 
    Market_volume = c(100L, 200L, 300L, 400L, 200L, 
    300L, 100L), Indicator_variable = c(1L, 0L, 0L, 0L, 
    0L, 0L, 0L),variable3=c(10L, 1L, 1L, 3L, 3L, 10L, 3L),variable4=c(2L, 1L, 1L, 3L, 3L, 8L, 3L)).Names = c("Org_ID", "Market_volume", "Indicator_variable","Var3","Var4"
), class = "data.frame", row.names = c(NA, -7L))

【问题讨论】:

  • “使用 (dplyr),我通过以下函数按 Org_ID 计算了按市场交易量计算的 NA 百分比” 您可能需要引用,因为代码是复制的直接来自here
  • UserR,我不知道可以引用。感谢 1. 帮助我回答上述问题,以及 2. 向我展示了如何引用。你的代码真的帮助了我!谢谢!
  • 通过引用,我的意思是链接到原始答案,并提到这是另一个问题的后续问题。请在您的问题正文中执行此操作,而不是将其作为评论发布。

标签: r loops subset


【解决方案1】:

您可以使用group_by %&gt;% filter 在不具体化聚合数据框的情况下进行过滤,并且在过滤器中您可以计算每个组的聚合条件:

df %>% 
    group_by(Org_ID) %>% 
    filter(sum(Market_volume * !Indicator_variable)/sum(Market_volume) > 0.3)

# A tibble: 7 x 5
# Groups:   Org_ID [2]
#  Org_ID Market_volume Indicator_variable  Var3  Var4
#   <int>         <int>              <int> <int> <int>
#1      1           100                  1    10     2
#2      1           200                  0     1     1
#3      1           300                  0     1     1
#4      3           400                  0     3     3
#5      3           200                  0     3     3
#6      3           300                  0    10     8
#7      3           100                  0     3     3

【讨论】:

  • 感谢 Pdiso!它工作得非常好。您知道如何将这些结果保存在数据 (df) 中,而无需将其写入为 csv 并重新读取到 R 中吗?
  • 你的意思是像this blog一样保存和加载。
  • 是的,现在我正在执行 write.csv (......, "data1.csv") 然后加载 data1.csv 文件。但我想我可以做 save() 功能。我会阅读参考!谢谢 Psidom!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多