【问题标题】:function with variable name in argument参数中有变量名的函数
【发布时间】:2021-12-09 03:44:23
【问题描述】:

我想创建一个可以应用于数据框的不同变量的函数。 这是数据框

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") 则不起作用

【问题讨论】:

    标签: r dataframe function


    【解决方案1】:

    如果你想在函数中使用它,你需要一些非标准的评估。

    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]] 访问传递的列名的值。

    【讨论】:

    • 谢谢!!第二点就是我要找的那个。
    猜你喜欢
    • 2023-03-06
    • 2016-01-01
    • 2012-10-04
    • 1970-01-01
    • 2014-12-28
    • 2018-05-23
    • 1970-01-01
    • 2017-01-23
    • 2011-06-27
    相关资源
    最近更新 更多