注释扩展功能的延迟评估 [英] Lazy evaluation to annotations expanding function

查看:54
本文介绍了注释扩展功能的延迟评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个函数来扩展组内的注释.

I wrote a function to expand annotations within groups.

function(data, group_col, expand_col){
  data %>%
    dplyr::group_by(!!rlang::ensym(group_col)) %>%
    dplyr::mutate( 
      !!rlang::ensym(expand_col) = dplyr::case_when(
        !is.na(!!rlang::ensym(expand_col)) ~ 
          !!rlang::ensym(expand_col) ,
        any( !is.na(!!rlang::ensym(expand_col))  ) & is.na(!!rlang::ensym(expand_col)) ~ 
          paste(unique(unlist(str_split(na.omit(!!rlang::ensym(expand_col)), " ")) ), collapse = " "),
        TRUE ~ 
          NA_character_  
      )
    ) %>%
    dplyr::ungroup()
}

这应该是这样的小标题:

This should take a tibble like this:

> t <- structure(list(a = c("a", "b", "c", "d", "e", "f", "g", "h"), 
    b = c(1, 1, 1, 1, 2, 2, 2, 2), c = c(NA, NA, NA, "D", "E", 
    NA, NA, NA)), row.names = c(NA, -8L), class = c("tbl_df", 
"tbl", "data.frame"))
> t
# A tibble: 8 x 3
  a         b c    
  <chr> <dbl> <chr>
1 a         1 NA   
2 b         1 NA   
3 c         1 NA   
4 d         1 D    
5 e         2 E    
6 f         2 NA   
7 g         2 NA   
8 h         2 NA  

使其成为现实:

> t %>%
+   dplyr::group_by(b) %>%
+   dplyr::mutate( 
+     c = dplyr::case_when(
+       !is.na(c) ~ c ,
+       any( !is.na(c)  ) & is.na(c) ~ 
+         paste(unique(unlist(str_split(na.omit(c), " ")) ), collapse = " "),
+       TRUE ~ 
+         NA_character_  
+     )
+   ) %>%
+   dplyr::ungroup()
# A tibble: 8 x 3
  a         b c    
  <chr> <dbl> <chr>
1 a         1 D    
2 b         1 D    
3 c         1 D    
4 d         1 D    
5 e         2 E    
6 f         2 E    
7 g         2 E    
8 h         2 E    

任何人都知道这种方法有什么问题,或者有更好的策略通过扩展一些先前分配的元素来在一个组中对元素进行评估.

Anyone knows whats is the problem with this approach or have any better strategy to assing element in a group by expanding some previously assigned element.

推荐答案

一种选择是将 curly-curly ( {{...}} )用于以更紧凑的方式做到这一点

An option would be to use curly-curly ({{...}}) for doing this in a more compact way

f1 <- function(data, group_col, expand_col){
  data %>%
    dplyr::group_by({{group_col}}) %>%
    dplyr::mutate( 
      {{expand_col}} := dplyr::case_when(
        !is.na({{expand_col}}) ~ 
          {{expand_col}} ,
      any( !is.na({{expand_col}})  ) & is.na({{expand_col}}) ~ 
        paste(unique(unlist(str_split(na.omit({{expand_col}}), " ")) ), 
                         collapse = " "),
      TRUE ~ 
        NA_character_  
    ))  %>%
    dplyr::ungroup()
}  



f1(t, b, c)
# A tibble: 8 x 3
#  a         b c    
#  <chr> <dbl> <chr>
#1 a         1 D    
#2 b         1 D    
#3 c         1 D    
#4 d         1 D    
#5 e         2 E    
#6 f         2 E    
#7 g         2 E    
#8 h         2 E    

这篇关于注释扩展功能的延迟评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆