【发布时间】:2021-09-29 01:52:24
【问题描述】:
好的,问题来了:我在 R 中编写了一个函数,它接受一个数据帧,然后使用 dplyr 和 tidyr 操作并返回另一个数据帧。
问题:我正在传递用引号、双引号或反引号 (``) 括起来的列名,但在这种情况下,R 会抛出一条错误消息,指出“错误:找不到对象‘对象名’”反引号或“错误:必须按在 .data 中找到的变量分组。* 未找到列 'column_variable`。”
第一个块:我通过 source() 导入的函数
cat_perc_by_dept <- function(data, group, category) {
# Returns the percentage of each category for a specific group.
# Inputs:
# data: the dataset with multiple groups and multiple categories for each group
# group: the specific group, eg department, that we want to focus on within group_col
# category: the category we want to focus on within a particular group
data %>%
select(DeptSpecialty, category) %>%
filter(DeptSpecialty == group) %>%
group_by(DeptSpecialty) %>%
mutate(Total = n(), Instance = 1) %>%
group_by(category) %>%
summarise(Perc = sum(Instance) / Total) %>%
distinct()
}
第二个:我在主文件中用引号调用它的函数
cat_perc_by_dept(data = visit_data, group = "Bariatrics", category = "ChargeDiagnosisCode")
还有反引号:
cat_perc_by_dept(data = visit_data, group = "Bariatrics", category = `ChargeDiagnosisCode`)
如何以不引发上述错误的方式将列名传递给函数?
【问题讨论】: