【问题标题】:dplyr using complete() in loop to retain factors levelsdplyr 在循环中使用 complete() 来保留因子级别
【发布时间】:2018-09-12 11:17:28
【问题描述】:

在循环中使用汇总后,我试图保留因子水平。 我使用模拟数据集复制了我的问题。

df = data.frame(a=rep(1:3,4), b=rep(1:2,6),c=rep(1:2,6),d=rep(1:2,6))
df$b = factor(df$b, levels=1:3)
#the group are for the loop. Since it's just an example have only 1 value
outer_group <- c("a") 
inner_group <- c("b")

我想要的输出是使用下面的代码实现的。但是,使用这种方法我需要手动更改complete() 的列,以防循环中有多个值

for (o in outer_group){
    for(i in inner_group){
        df %>%
            group_by_at(i) %>%
            summarise(count_a=length(!!o)) %>%
            complete(b) -> a
    }

}

为此,我尝试将其更改为complete(!!i),例如

for (o in outer_group){
    for(i in inner_group){
        df %>%
            group_by_at(i) %>%
            summarise(count_a=length(!!o)) %>%
            complete(!!i) -> a
    }

}

不幸的是,这不起作用

Error: `by` can't contain join column `"b"` which is missing from RHS

感谢任何帮助

期望的输出:

# A tibble: 3 x 2                                  
  b     count_a
  <fct>   <int>
1 1           1
2 2           1
3 3          NA

【问题讨论】:

  • 不确定这是否是您想要的,但您可以使用以下命令获得所需的输出:df %&gt;% group_by(b) %&gt;% summarize(n()) %&gt;% complete(b) 如果这是您想要的,我认为这是 stackoverflow.com/questions/22523131/… 的副本
  • 链接的帖子不使用循环,因此,这不是我要找的。如果没有需要采用的循环,这种方法就可以工作

标签: r dplyr


【解决方案1】:

您可以使用 wrapr::let 代替 dplyr 引用机制:

library(wrapr)
for (o in outer_group){
   for(i in inner_group){
     let(c(I=i),
        df %>%
          group_by_at(i) %>%
          summarise(count_a=length(!!o)) %>%
          complete(I) -> a)
    }
}
## A tibble: 3 x 2
#  b     count_a
#  <fct>   <int>
#1 1           1
#2 2           1
#3 3          NA

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2023-03-18
    • 2018-02-17
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多