Home > Net >  Trying to write a function that takes a data frame and a column to create a new numeric column based
Trying to write a function that takes a data frame and a column to create a new numeric column based

Time:08-11

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)

CodePudding user response:

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
  •  Tags:  
  • r
  • Related