Create a new variable for each time point in R

Viewed 118

I have a wide dataset with variables measured at different time points. Each variable has many columns in the dataset and the number at the end of the columns indicates de timepoint when the data was collected (ex. a.1 , a.2, a.3 etc). I would like to create a new variable for each timepoint, using the same formula on the same variables. How could I code this by using only one formula applied for each time point, instead of repeating the same code for each timepoint, as in the example below?

df$a.1 <- (df$b.1 + df$c.1)/2

df$a.2 <- (df$b.2 + df$c.2)/2

df$a.3 <- (df$b.3 + df$c.3)/2

df$a.4 <- (df$b.4 + df$c.4)/2

Thanks

1 Answers

We could subset the b columns, get the corresponding c columns and do the mean and assign back to new columns, paste is vectorized as well as + and /

df[paste0("a.", 1:4)] <- (df[paste0("b.", 1:4)] + df[paste0("c.", 1:4)])/2

It may also be possible with across by looping over the 'b', columns, then get the corresponding 'c' columns and change the names in .names to create new columns

library(dplyr)
library(stringr)
df <- df %>%
      mutate(across(starts_with('b.'), ~ 
                (. + get(str_replace(cur_column(), 'b', 'c')))/2,
              .names = "{str_replace(.col, 'b', 'a')}"))
Related