'Using paste0 in deriving the denominator from the numerator using column names in dplyr mutate across

I am trying to create a function that takes in as numerator a column using column name and denominator using the same column name but includes a character and call the function in dplyr mutate across.

This is my attempt:

mtcars <- data.frame(f1_nom = c(1,2,5,7), f2_nom = c(3,4,2,8),f3_nom = c(1,2,5,7), f4_nom = c(3,4,2,8),f5_nom = c(2,3,5,1), f6_nom = c(3,4,3,7), f7 = c(1,2,4,7),
                     f1_nom_wt = c(1,3,1,2),f2_nom_wt = c(6,8,5,9),f3_nom_wt = c(1,1,1,2),f4_nom_wt = c(3,3,3,2),f5_nom_wt = c(5,8,5,1),f5_nom_wt = c(6,11,1,2))

library(rlang)
f <- function(var, colName){
  (fld+1)/(colName+1)
}
mtcars %>%
  mutate(across(f1_nom:f6_nom, ~ f(.x, paste0(.x,"_wt")), .names = "{col}_xyz"))

What I want is for the function to do this:

f1_nom/f1_nom_wt

I have over a two hundred of these rows f1_nom:f100_nom and f1_nom_wt:f100_nom_wt.

I know am doing it wrong cos am passing a var and characters paste0.

Thanks in advance for your help.



Solution 1:[1]

Well, / can directly be applied on a dataframe. We can create two groups of dataframe and divide them directly.

wt_cols <- grep('wt', names(df), value = TRUE)
cols <- sub('_wt', '', wt_cols)
df[paste0(cols, '_xyz')] <- df[cols]/df[wt_cols]
df

data

df <- data.frame(f1_nom = c(1,2,5,7), f2_nom = c(3,4,2,8),f3_nom = c(1,2,5,7), 
                 f4_nom = c(3,4,2,8),f5_nom = c(2,3,5,1), f6_nom = c(3,4,3,7),
                 f1_nom_wt = c(1,3,1,2),f2_nom_wt = c(6,8,5,9),f3_nom_wt = c(1,1,1,2),
                 f4_nom_wt = c(3,3,3,2),f5_nom_wt = c(5,8,5,1),f6_nom_wt = c(6,11,1,2))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronak Shah