user15950867
user15950867

Reputation: 35

Create multiple variables from existing variables variables using a statistical method simultaneously in R

Using bloms' formula, I created a new variable from an existing one whilst keeping them both in the DF thusly:

DF$R_BLR<-blom(DF$R, method = "blom")

I have 7 other variables (S,T,U,V,W,X,Y, to create new ones (S_BLR T_BLR etc) whilst keeping the originals) I want to perform the same operation on and was wondering if there is a way I could do it in one go rather than type them all out as per the first one.

The existing vars are all next to each other in the DF (columns 1-7). I have tried using the mutate function, as this worked previously when I wanted to recode categories in other variables, but this is just a straight transformation and I can't quite figure out the syntax.

Upvotes: 1

Views: 54

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

Using lapply -

new_cols <- paste0(names(df)[1:7], '_BLR')
df[new_cols] <- lapply(df[1:7], blom, method = "blom")

Upvotes: 1

TimTeaFan
TimTeaFan

Reputation: 18551

We can use dplyr::across, here is an example:

library(dplyr)
library(rcompanion)

# from `?blom`'s examples
Value = c(709,679,699,657,594,677,592,538,476,508,505,539)
Sex   = c(rep("Male",3), rep("Female",3), rep("Male",3), rep("Female",3))
Fat   = c(rep("Fresh", 6), rep("Rancid", 6))

Sokal = data.frame(Value, Sex, Fat)

# dplyr::across with the example above (one varialbe)

Sokal %>% 
  mutate(across(Value, list(BLR = ~ blom(.x, method = "blom"))))
#>    Value    Sex    Fat  Value_BLR
#> 1    709   Male  Fresh  1.6350393
#> 2    679   Male  Fresh  0.7916386
#> 3    699   Male  Fresh  1.1139372
#> 4    657 Female  Fresh  0.3119191
#> 5    594 Female  Fresh  0.1024905
#> 6    677 Female  Fresh  0.5361763
#> 7    592   Male Rancid -0.1024905
#> 8    538   Male Rancid -0.5361763
#> 9    476   Male Rancid -1.6350393
#> 10   508 Female Rancid -0.7916386
#> 11   505 Female Rancid -1.1139372
#> 12   539 Female Rancid -0.3119191

# applying this example to your data.frame
your_df <- setNames(as.list(1:8), LETTERS[18:25]) %>% as_tibble

# using tidyselect `matches()` with a regex in `across`
your_df %>% 
  mutate(across(matches("[R-Y]"),
                list(BLR = ~ blom(.x, method = "blom"))))

# or select variables by position in `across`
your_df %>% 
  mutate(across(1:7,
                list(BLR = ~ blom(.x, method = "blom"))))

Created on 2021-07-24 by the reprex package (v0.3.0)

Upvotes: 0

Related Questions