r - 参数中有变量名的函数
问题描述
我想创建一个可以应用于数据框的不同变量的函数。这是数据框
data=data.frame(V1=c(0,25,6,"NC", 9, 10, "", "", 15), V2=c(47,"NC",56,"NC", "", 42, "", 48, ""), V3=c(2,5,3,4, 9,5, "", "", 2))
> data
V1 V2 V3
1 0 47 2
2 25 NC 5
3 6 56 3
4 -9 NC 4
5 9 9
6 10 42 5
7 -9
8 -9 48
9 15 2
这是我想包含在我的函数中的操作(clin=function(data,variable_name))
data$V1=as.numeric(data$V1)
data$V1[is.na(data$V1)]=-9
data_V1 = data %>% mutate(tot=n()) %>%
mutate(rep= ifelse(V1==-9, "no_value", "value")) %>%
mutate(sum_value=ifelse(rep=="value", sum(rep=="value"), tot-sum(rep=="value"))) %>%
mutate(variable="V1") %>%
select(variable, rep, sum_value) %>%
distinct(rep, .keep_all=TRUE)
我的问题是如何在函数内部调用变量名。如果我使用 clin(data, "V1") 它不起作用
解决方案
如果你想在一个函数中使用它,你需要一些非标准的评估。
library(dplyr)
clean =function(data, variable_name) {
data %>%
mutate(!!variable_name := suppressWarnings(as.numeric(.data[[variable_name]])),
!!variable_name := replace(.data[[variable_name]], is.na(.data[[variable_name]]), -9),
tot = n(),
rep= ifelse(.data[[variable_name]] ==-9, "no_value", "value"),
sum_value=ifelse(rep=="value", sum(rep=="value"), tot-sum(rep=="value")),
variable=variable_name) %>%
select(variable, rep, sum_value) %>%
distinct(rep, .keep_all=TRUE)
}
clean(data, "V1")
# variable rep sum_value
#1 V1 value 6
#2 V1 no_value 3
clean(data, "V2")
# variable rep sum_value
#1 V2 value 4
#2 V2 no_value 5
总结一下——
- 一个
mutate
声明就足够了。 !!variable_name :=
在左侧使用来分配列名。- 用于
.data[[variable_name]]
访问传递的列名的值。