rfunctionmutated

mutate not adding the correct column name when performing calculation


When I try to add a column within a function using inputs from the function, a column is added with the wrong name. Here is a sample of the data:

AllGlut1 <- data.frame(Date = c("11/1/2021", "11/2/2021", "11/3/2021"), Row = c(3, 6, 8), d.15N.14N = c(-4.593, -4.427, -4.436))

known <- "d15N_known"
RefMaterials <- data.frame(d15N_known = c(6.485, 2.632, 9.235), d13C_known = c(-21.523, -23.344, -24.892))

colm <- "d.15N.14N"

driftcorr <- function(colm, known, df){

AllGlut1 <- AllGlut1 %>% mutate(res_drift = RefMaterials[1,known] - AllGlut1[colm])

return(AllGlut1)
}

results <- driftcorr(colm, known, AllGlut1)

When I just do:

res_drift <- RefMaterials[1,known] - AllGlut1[colm]

in the console, it works perfectly fine.

Anybody know what is happening here?


Solution

  • Use [, colm] instead of [colm] to reference the column of AllGlut1:

    driftcorr <- function(colm, known, df){
      AllGlut1 <- AllGlut1 %>%
        mutate(res_drift = RefMaterials[1,known] - AllGlut1[, colm])
      return(AllGlut1)
    }
    

    or, as @Martin Gal says, use RefMaterials[1,known] - !!sym(colm) (I checked, it does work ...)

    It looks like you're using a mixture of base-R and tidyverse approaches, which can potentially get confusing ...