【问题标题】:Creating multiple columns depending on others in tidyverse根据 tidyverse 中的其他列创建多个列
【发布时间】:2022-09-23 01:36:41
【问题描述】:

我有一个数据集如下:

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 

我想创建一组新的列:

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\"

用这些列的绝对值。我怎样才能做到这一点? 因为我可以使用一个简单的 mutate,但它太冗长了。

最后,我还想创建一组列来指示相对列是负数还是正数。 (如果为正则为 1,否则为 0)

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

    标签: r tidyverse


    【解决方案1】:

    我们可以使用mutateacross

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2023-01-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多