我有这样的数据:
(test <- tribble(
~case, ~A.1_recipient, ~A.2_recipient, ~A.1_donor, ~A.2_donor,
1, "HLA-A2", "HLA-A3", "HLA-A2", "HLA-A68",
2, "A2", "HLA-A3", "A3", "A69",
3, "A11", "A24", "HLA-A2", NA,
4, "A66", NA, "A2", "A24"
))我经常使用代码从值中删除前缀:
(test_code <- test
%>% mutate(A.1_recipient = str_replace(A.1_recipient, "HLA-", ""))
)我还使用tidyselect将函数应用于多个列:
(test_code <- test
%>% mutate(across(A.1_recipient:A.2_donor, ~str_replace(., "HLA-", "")))
)
(test_code <- test
%>% mutate(across(ends_with("recipient"), ~str_replace(., "HLA-", "")))
)我想把它开发成一个函数,它可以处理单个列的输入或tidyselect。使用此链接(https://cran.r-project.org/web/packages/tidyselect/vignettes/tidyselect.html),我尝试了以下功能:
HLA_prefix_remove <- function(.data, ...) {
# Remove any HLA and locus prefixes from typing results.
expr <- rlang::expr(c(...))
pos <- eval_select(expr, data = .data)
.data <- .data %>%
mutate(.data[pos], ~str_replace(pos, "HLA-", ""))
}我试图用以下代码运行该代码:
(test_function <- test
%>% HLA_prefix_remove(A.1_recipient)
)但是,我得到以下错误:
Error in `mutate()`:
! Problem while computing `..1 = .data[pos]`.
Caused by error in `.data[pos]`:
! `[` is not supported by the `.data` pronoun, use `[[` or $
instead.
Backtrace:
1. test %>% HLA_prefix_remove(A.1_recipient)
10. rlang:::`[.rlang_data_pronoun`(.data, pos)
Error in mutate(., .data[pos], ~str_replace(pos, "HLA-", "")) :
Caused by error in `.data[pos]`:
! `[` is not supported by the `.data` pronoun, use `[[` or $
instead.不知道如何编写函数以正确传递参数?
发布于 2022-08-22 17:13:40
使用c(.)就像这样:
library(dplyr)
library(stringr)
HLA_prefix_remove2 <- function(.data, ...) {
.data %>% mutate(across(c(...), ~str_replace(., "HLA-", "")))
}
HLA_prefix_remove2(test, A.1_recipient:A.2_donor)
HLA_prefix_remove2(test, ends_with("recipient"))
HLA_prefix_remove2(test, c(A.1_recipient, A.2_recipient))
HLA_prefix_remove2(test, A.1_recipient, A.2_recipient)如果有一个单独的第二个参数是可以的,那么这也可以:
HLA_prefix_remove3 <- function(.data, sel) {
.data %>% mutate(across({{sel}}, ~str_replace(., "HLA-", "")))
}
HLA_prefix_remove3(test, A.1_recipient:A.2_donor)
HLA_prefix_remove3(test, ends_with("recipient"))
HLA_prefix_remove3(test, c(A.1_recipient, A.2_recipient))发布于 2022-08-22 16:23:49
我们可以将函数更改为
library(rlang)
library(dplyr)
library(purrr)
library(stringr)
HLA_prefix_remove <- function(.data, ...) {
colnms <- map_chr(rlang::ensyms(...), as_string)
.data %>%
mutate(across(all_of(colnms), ~str_replace(.x, "HLA-", "")))
}-testing
test %>%
HLA_prefix_remove(A.1_recipient)
# A tibble: 4 × 5
case A.1_recipient A.2_recipient A.1_donor A.2_donor
<dbl> <chr> <chr> <chr> <chr>
1 1 A2 HLA-A3 HLA-A2 HLA-A68
2 2 A2 HLA-A3 A3 A69
3 3 A11 A24 HLA-A2 <NA>
4 4 A66 <NA> A2 A24
test %>%
HLA_prefix_remove(A.1_recipient, A.2_recipient)
# A tibble: 4 × 5
case A.1_recipient A.2_recipient A.1_donor A.2_donor
<dbl> <chr> <chr> <chr> <chr>
1 1 A2 A3 HLA-A2 HLA-A68
2 2 A2 A3 A3 A69
3 3 A11 A24 HLA-A2 <NA>
4 4 A66 <NA> A2 A24 https://stackoverflow.com/questions/73448162
复制相似问题