【问题标题】:Multiple tidying operations in one pipeline一个管道中的多个整理操作
【发布时间】:2017-07-29 00:14:37
【问题描述】:

这更像是我现在正在做的代码清理练习。我的初始数据是这样的:

Year    County    Town  ...  Funding Received ... (90+ Variables total)
2016      a        x               Yes
2015      a        y               No
2014      a        x               Yes
2016      b        z               Yes

我看不到如何从中获取已提交和批准的申请的计数,因此我将其转换为指标变量以使用以下代码进行计数:

counties <- original_data %>%
  select(county, funded, year) %>%
  mutate(
    a=ifelse(county == "a", 1,0),
    b=ifelse(county == "b", 1,0),
    c=ifelse(county == "c", 1,0),
    ... etc ...
  )

输出看起来像

County    Funding Received    Year    binary.a    binary.b
  a             Yes           2016       1           0
  a             No            2015       1           0
  b             No            2016       0           1

然后将此数据转换为两个数据框(已提交和已资助),以使用以下代码计算每个县每年已提交和已资助的申请:

countysum <- counties %>%
  select(-funded) %>%
  group_by(county, year) %>%
  summarise_all(sum, na.rm = T)

输出如下:

County    Year    sum.a    sum.b
  a       2016      32       0
  a       2015      24       0
  b       2016       0      16

但是为了以更简洁的格式获取数据,我使用了更多命令:

countysum$submitted <- rowSums(countysum[,3:15, na.rm = T) #3:15 are county indicator vars
countysum <- countysum[,-c(3:19)]

现在我的问题是:有没有办法将所有这些操作简化为一个单一的管道?现在我有可以工作的代码,但更希望有可以工作并且更容易理解的代码。抱歉,数据不足,无法分享。

【问题讨论】:

  • 看看tidyr::spread - 我认为这就是您在第一部分中尝试做的事情
  • 请展示一个可重现的小例子。在您的代码中,有funded,但在示例中,它没有显示
  • @akrun 我的错,funded 对应原帖中的“Funding Received”。

标签: r dplyr pipeline


【解决方案1】:

我不确定我是否完全理解您最终想要的输出是什么样的,但我认为您可以利用逻辑值被强制转换为整数并跳过虚拟列的创建这一事实。

library(dplyr)

byyear  <- original_data %>% 
   group_by(county, year) %>% 
   summarize(
       wasfunded = any(funded == "Yes", na.rm = T)
     , submittedapplication = any(submittedapp == "Yes", na.rm = T) # I'm assuming did/didn't submit is one of the other variables
   ) 

# if you don't need the byyear data for something else (I always seem to), 
# you can pipe that straight into this next line
yrs_funded_by_county  <- byyear %>% 
  summarize(
      n_yrs_funded = sum(wasfunded)
    , n_yrs_submitted = sum(submittedapplication)
    , pct_awarded = n_yrs_funded/n_yrs_submitted  # maybe you don't need a award rate, but I threw it it b/c it's the kind of stuff my grant person cares about
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    相关资源
    最近更新 更多