gpt4 book ai didi

r - 函数从字面上接受一个参数而不是参数的值

转载 作者:行者123 更新时间:2023-12-04 08:15:39 24 4
gpt4 key购买 nike

我尝试创建一个函数,该函数将根据每个人拥有的唯一 PATIENT_ID 数量按降序返回 x 最大分子。从某个日期到最后一个日期。

data <- data.frame(PATIENT_ID = c(1,1,2,2), dateM = c(ymd("2020-01-05","2020-01-06","2020-05-06","2019-12-15")), MOLECULES = c("mol1", "mol1", "mol1", "mol2"))


topx <- function(data, datefrom, var , x = 5){
data %>%
subset(dateM >= datefrom) %>%
group_by(var) %>%
summarize(pat = length(unique(PATIENT_ID))) %>%
arrange(-pat) %>%
head(x) %>%
select(1)
}

topx(data = data, datefrom = "2016-04", var = MOLECULES, x = 2)
在这种情况下,想要的结果是:
c("mol1","mol2")
但是,它将 var 作为文本并且不解析 MOLECULES 并告诉我。
 Error: Must group by variables found in `.data`.
* Column `var` is not found.

最佳答案

很酷的功能。用dplyr编程时有一些特殊的规则和操作.查看更多 here .具体来说,您需要 {{}}运算符(operator)。


library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union

data <- data.frame(PATIENT_ID = c(1,1,2,2), dateM = c(ymd("2020-01-05","2020-01-06","2020-05-06","2019-12-15")), MOLECULES = c("mol1", "mol1", "mol1", "mol2"))

topx <- function(data, datefrom, var , x = 5){
data %>%
subset(dateM >= datefrom) %>%
group_by({{var}}) %>%
summarize(pat = length(unique(PATIENT_ID))) %>%
arrange(-pat) %>%
head(x) %>%
select(1)
}

topx(data = data, datefrom = "2016-04-01", var = MOLECULES, x = 2)
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 2 x 1
#> MOLECULES
#> <chr>
#> 1 mol1
#> 2 mol2
创建于 2021-01-14 由 reprex package (v0.3.0)

关于r - 函数从字面上接受一个参数而不是参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65718923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com