mistermike37
mistermike37

Reputation: 1

Mutate multiple columns in R (tidyverse)

I have a small problem with R. I have merged together 2 datasets and I have to compute simple ratios between them. The datasets are not that small (18 columns per dataset) and I would like to avoid going by simple brute force.

To give you an example

df <- data.frame(a1= sample(1:100, 10), b1 = sample(1:100, 10), a2= sample(1:100, 10), b2 = sample(1:100,10)) 

The ratios would simply be a column divided by another one, so in the example it would be c1=a1/b1 and c2=a2/b2. And it could be simply implemented by:

mutate(df, c1=a1/b1, c2=a2/b2)

My question is if there is a way to make this process automatic and instruct R to perform a mutate without manually inputting all the formulas such that it computes c1,c2,c3.... c18.

I've tried setting up a for cycle with subsets on the columns but I can't seem to make it work within tidyverse.

Thank you in advance

Upvotes: 0

Views: 230

Answers (1)

Phil
Phil

Reputation: 8127

One simple base R way would be to do something like:

for (i in 1:2) {
  df[paste0("c", i)] <- df[paste0("a", i)] / df[paste0("b", i)] 
}

But it's dependent on what pattern your actual variable names have.

Another way using tidyverse tools (but there's probably a more elegant way of doing this):

library(tidyverse)
library(glue)

map_dfc(1:2, function(x) {
  transmute(df, "c{x}" := .data[[glue("a{x}")]] / .data[[glue("b{x}")]])
}) %>% 
  bind_cols(df) %>% 
  relocate(starts_with("c"), .after = last_col())

Upvotes: 0

Related Questions