-3
d3= data.frame(c1=  c("Y","N" ), c2 = c("Y","N"))

fun=function(df1,col1,col2){
  df1 <- df1 %>% mutate(c3 = case_when(col1 == as.character("Y") ~ 1, col1 == as.character("N") ~ 0))
  df1 <- df1 %>% mutate(c4 = case_when(col2 == as.character("Y") ~ 2, col2== as.character("N") ~ -1))
  return(df1)
}
d4=fun(d3,as.character("c1"),as.character("c2"))
head(d4)
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
lolbye
  • 67
  • 5
  • See these questions about how to pass column names to functions: [Implementing mutate within a function called with variables](https://stackoverflow.com/questions/71384696/implementing-mutate-within-a-function-called-with-variables/71384913); [How to pass column name as an arguments in the function](https://stackoverflow.com/questions/70945180/how-to-pass-column-name-as-an-arguments-in-the-function) – zephryl Aug 11 '22 at 05:18
  • I don't understand what you're trying to do. Can you show your expected output? Is that `d4`? Also you don't need any of those `as.character()` statements; `"c1"` is already a character scalar. – Maurits Evers Aug 11 '22 at 05:30
  • @MauritsEvers sorry if it was unclear. Basically, I'm trying to create a function that creates a new column based on the existing column (if Y is present in c1, c3 should contain 1). yes d4 is the output. I realized i didn't need as.character() my bad. can you please provide the right solution – lolbye Aug 11 '22 at 05:37

1 Answers1

1
library(tidyverse)

d3 <- data.frame(c1 =  c("Y","N" ), c2 = c("Y","N"))

fun <- function(df1, col1, col2){
    
    df1 <- df1 %>% 
        mutate(c3 = case_when({{col1}} == "Y" ~ 1, 
                              {{col1}} == "N" ~ 0),
               c4 = case_when({{col2}} == "Y" ~ 2, 
                              {{col2}} == "N" ~ -1)
        )
    
    return(df1)
}

d4 <- fun(d3, c1, c2)
> head(d4)
  c1 c2 c3 c4
1  Y  Y  1  2
2  N  N  0 -1
AlpacaKing
  • 371
  • 2
  • 10
  • 1
    This is not a good implementation: repeatedly referring to `df1` inside `mutate` kind of defeats the purpose of chaining commands (and is certainly un-tidy). Better to use NSE, which is the `tidyverse` way. Also, if you do use `tidyverse` functionality I recommend using the `magrittr` chain operator `%>%` rather than the new base R operator. The former is more flexible, and more canonical when using `dplyr` verbs. – Maurits Evers Aug 11 '22 at 05:59
  • 1
    OK. Thanks. The code had been amended. – AlpacaKing Aug 11 '22 at 08:49