2

I am trying to use rowwise %>% mutate_at(ifelse()), I had previously successfully got this to work with dplyr version < 1.0.0 using mutate_at, but am unsure how to accomplish it using its new across function.

Here is a subset of rows and columns from my data frame

data <- data.frame(level_1_name = c("coverage.modifier", "coverage.modifier", "something_else"),
                   level_1_type = c("static", "static", "static"),
                   level_1_a = c(NA, "1", "2"),
                   level_2_name = c("something_else", "something_else", "something_else"),
                   level_2_type = c("static", "static", "static"),
                   level_2_a = c(NA, "1", "2"),
                   stringsAsFactors = F)

And what I want to accomplish can be done with the following

library(dplyr) ; library(rlang) ; library(tidyselect) ; library(magrittr)
data %>%
    rowwise() %>%
    mutate_at(vars(which(grepl(pattern = "coverage.modifier", .)) + 2),
              funs(ifelse(eval_tidy(sym(gsub("_a", "_name", as_name(quo(.))))) == "coverage.modifier" && is.na(.), "", .))) %>%
    ungroup()

with the output

# A tibble: 3 x 6
  level_1_name      level_1_type level_1_a level_2_name   level_2_type level_2_a
  <chr>             <chr>        <chr>     <chr>          <chr>        <chr>    
1 coverage.modifier static       ""        something_else static       NA       
2 coverage.modifier static       "1"       something_else static       1        
3 something_else    static       "2"       something_else static       2     

how can I recreate this using mutate and c_across instead of mutate_at? Thank you!

4

1 回答 1

2

如果我理解正确,您希望获取名称为 ' {something} _a'的所有列并将NAs替换为 ,但仅限于名为 ' {something} _name'''的相应列具有 value 的行上。'coverage.modifier'

这是一种方法across

data %>%
    mutate(across(ends_with('_a'),
                  ~replace(.,
                           is.na(.) &
                               grepl('coverage.modifier',
                                     cur_data()[[sub('_a$', '_name', cur_column())]]),
                           '')))
于 2020-06-10T01:30:11.357 回答