Norhther
Norhther

Reputation: 500

Creating multiple columns depending on others in tidyverse

I have a dataset as follows:

Squat1Kg Squat2Kg Squat3Kg Bench1Kg Bench2Kg Bench3Kg Deadlift1Kg Deadlift2Kg Deadlift3Kg
      <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>       <dbl>       <dbl>       <dbl>
 1       75       80     -90      50       55       60           95          105        108.
 2       95      100     105      62.5     67.5    -72.5        100          110       -120 
 3       85       90     100      55       62.5    -65           90          100        105 
 4      125      132     138.    115      122.    -128.         150          165        170 
 5       80       85      90      40       50      -60          112.         120        125 
 6       90      -95     100      60      -65      -67.5         90          105        115 
 7       85       95     100      40       47.5    -50          115          130        140 
 8      210      225     232.    150      160     -165          240          260       -270 

I want to create a new set of columns:

paste0("WeightTried_", colnames(df_aux[,7:15]))
[1] "WeightTried_Squat1Kg"    "WeightTried_Squat2Kg"    "WeightTried_Squat3Kg"   
[4] "WeightTried_Bench1Kg"    "WeightTried_Bench2Kg"    "WeightTried_Bench3Kg"   
[7] "WeightTried_Deadlift1Kg" "WeightTried_Deadlift2Kg" "WeightTried_Deadlift3Kg"

With the absolute value of these columns. How can I accomplish this? Because I could use a simple mutate, but it's too verboose.

Finally, I would like to also create a set of columns that indicates if the relative column is negative or positive. (1 if it's positive, 0 otherwise)

paste0("Lifted", colnames(df_aux[,7:15]), "?")

Upvotes: 1

Views: 33

Answers (1)

akrun
akrun

Reputation: 886938

We may use mutate with across

df_aux <- df_aux %>%
   mutate(across(7:15, abs, .names = "WeightTried_{.col}"),
          across(7:15, ~ +(.x >0), .names = "Lifted_{.col}"))

Upvotes: 1

Related Questions