Home > OS >  Converting a dplyr transformation command into a base R function
Converting a dplyr transformation command into a base R function

Time:07-09

I have a dplyr command that works great on its own:

XOR1 <- XOR1 %>%
  mutate(XOR_inter = case_when(
    chr18.27348077_G == 0 & chr18.32316331_A == 0 ~ 0,
    chr18.27348077_G == 0 & chr18.32316331_A == 1 ~ 1,
    chr18.27348077_G == 0 & chr18.32316331_A == 2 ~ 0,
    chr18.27348077_G == 1 & chr18.32316331_A == 0 ~ 1,
    chr18.27348077_G == 1 & chr18.32316331_A == 1 ~ 0,
    chr18.27348077_G == 1 & chr18.32316331_A == 2 ~ 1,
    chr18.27348077_G == 2 & chr18.32316331_A == 0 ~ 0,
    chr18.27348077_G == 2 & chr18.32316331_A == 1 ~ 1,
    chr18.27348077_G == 2 & chr18.32316331_A == 2 ~ 0
  ))

Basically, it checks for two conditionals in the column names (chr18.27348077_G & chr18.32316331_A) and outputs a desired value into a new column based on the combination of these columns' values. It works perfectly but I want to convert this heavy code into a function I can call within a loop. I tried to convert it as follows:

FunXOR <- function(df, X1, X2) {
  df <- df %>%
    mutate(XOR_inter = case_when(
      X1 == 0 & X2 == 0 ~ 0,
      X1 == 0 & X2 == 1 ~ 1,
      X1 == 0 & X2 == 2 ~ 0,
      X1 == 1 & X2 == 0 ~ 1,
      X1 == 1 & X2 == 1 ~ 0,
      X1 == 1 & X2 == 2 ~ 1,
      X1 == 2 & X2 == 0 ~ 0,
      X1 == 2 & X2 == 1 ~ 1,
      X1 == 2 & X2 == 2 ~ 0
    ))
}

FunXOR(XOR1, "chr18.27348077_G", "chr18.32316331_A")

It runs without an error but nothing happens (i.e. no new column in generated). I've read that dplyr syntax doesn't work great with normal R function syntax. I was hoping to get help in converting this to a function for ease of use later

CodePudding user response:

You can use {{var}} to pass unquoted variable names.

Additionally, if you want to update your data.frame instead of outputting to the console, you can assign to the current data.frame.

library(dplyr)

XOR1 <- data.frame(
  chr18.27348077_G = c(0,1,2),
  chr18.32316331_A = c(0,1,2)
)

FunXOR <- function(df, X1, X2) {
  df <- df %>%
    mutate(XOR_inter = case_when(
      {{X1}} == 0 & {{X2}} == 0 ~ 0,
      {{X1}} == 0 & {{X2}} == 1 ~ 1,
      {{X1}} == 0 & {{X2}} == 2 ~ 0,
      {{X1}} == 1 & {{X2}} == 0 ~ 1,
      {{X1}} == 1 & {{X2}} == 1 ~ 0,
      {{X1}} == 1 & {{X2}} == 2 ~ 1,
      {{X1}} == 2 & {{X2}} == 0 ~ 0,
      {{X1}} == 2 & {{X2}} == 1 ~ 1,
      {{X1}} == 2 & {{X2}} == 2 ~ 0
    ))
  return(df)
}

FunXOR <- FunXOR(XOR1, chr18.27348077_G, chr18.32316331_A)

The returned value with this sample data is:

> FunXOR(XOR1, chr18.27348077_G, chr18.32316331_A)
  chr18.27348077_G chr18.32316331_A XOR_inter
1                0                0         0
2                1                1         0
3                2                2         0
  • Related