【问题标题】:use for loop with pipes in R在R中使用带有管道的for循环
【发布时间】:2023-03-14 11:00:01
【问题描述】:

我正在使用 magrittr 库在 R 中使用管道。我需要在管道之间使用for循环,我该怎么做

tmrank.ft <- regulartable(
data = tm.rank.out) %>% 
theme_booktabs() %>% 
autofit() %>%
merge_v(j=missing_species) %>%
align(align = 'center') %>%
align(align = 'center', part = 'header') %>% 
bold(part = 'header') %>%
height(height = 1, part = 'header') %>% 
fontsize(size = 14, part = 'all') %>% 
width(j=1, width = 1.0 ) %>%
width(j=2:ncol(tm.rank.out), width = 2.5) %>%
{
for (ii in 2:length(species))
{
  group_result <- group_vector(tm.rank.out.temp, grp.type, species[ii])
  for (jj in 1:length(group_result))
  {
    text_color <- grp.clr[[unique(grp.type[,grp][jj])]]
    color(i = group_result[[jj]], j = ~ species[ii], color = text_color)
  }
}
}

它把我扔了

继承错误(x,“flextable”): 缺少参数“x”,没有默认值

【问题讨论】:

    标签: r pipe


    【解决方案1】:

    管道需要第一个参数为x 的函数。因此,只需使用参数x 预先定义函数即可:

    foo <- function(x){
      for (ii in 2:length(species))
    {
      group_result <- group_vector(tm.rank.out.temp, grp.type, species[ii])
      for (jj in 1:length(group_result))
      {
        text_color <- grp.clr[[unique(grp.type[,grp][jj])]]
        color(i = group_result[[jj]], j = ~ species[ii], color = text_color)
      }
     }
    }
    
    tmrank.ft <- regulartable(
    data = tm.rank.out) %>% 
    theme_booktabs() %>% 
    autofit() %>%
    merge_v(j=missing_species) %>%
    align(align = 'center') %>%
    align(align = 'center', part = 'header') %>% 
    bold(part = 'header') %>%
    height(height = 1, part = 'header') %>% 
    fontsize(size = 14, part = 'all') %>% 
    width(j=1, width = 1.0 ) %>%
    width(j=2:ncol(tm.rank.out), width = 2.5) %>%
    foo()
    

    【讨论】:

    • 函数必须返回“x”。我就是这样做的。
    【解决方案2】:

    希望代码可以帮助到你。

    seq(1:10) %>% (function(x){
        print(x)
    })
    

    here正在谈论这个方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2019-03-10
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多