简体   繁体   English

Function 使用 mutate 和 case_when 创建二分法 var (0/1)

[英]Function to create dichotomic var (0/1) using mutate and case_when

I'm trying to create a function that will recode variables with categories 1 / 2 into 0 / 1. Something like this:我正在尝试创建一个 function ,它将类别 1 / 2 的变量重新编码为 0 / 1。像这样:

var_dic <- function(data, x){
  mutate(x_rec, case_when(
              x == 1 ~ 1,
              x == 2 ~ 0,
              TRUE ~ NA_real_))
}

var1 <- c('1', '2', '1', '1', '2', NA, '2', NA)
var2 <- c('1', '1', '2', '2', '2', NA, '2', NA)
id <- c(1,2,3,4,5,6, 7, 8)
testing.df <- data.frame(id, var1, var2)

But I'm getting an error related to 'x_rec'.但我收到与“x_rec”相关的错误。 I want that part of the code to establish the name of the new var.我希望这部分代码建立新变量的名称。 I'm guess i should include paste0 somewhere, but not sure how or where in the code.我猜我应该在某处包含 paste0,但不确定代码中的方式或位置。

We can use the data as well我们也可以使用data

var_dic <- function(data, x){
   data %>%
      mutate(!! {{x}} := case_when(
          {{x}} == 1 ~ 1,
          {{x}} == 2 ~ 0,
          TRUE ~ NA_real_))
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM