[英]function with variable name in argument
我想創建一個可以應用於數據框不同變量的函數。 這是數據框
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]]
訪問傳遞的列名的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.