Home > database >  Using mutate() and across() to create a column based on two others in R
Using mutate() and across() to create a column based on two others in R

Time:02-03

I just got this example df:

df = data.frame(A1 = c(1,2,3),
                A2 = c(4,5,6))

And I'm trying to divide each of these "A" columns by the average of the entire column

First of all, i need a mean column:

df %>%
  mutate(
    across(matches("A"), ~ mean(.x), .names = "mean_{col}"  )
  )

But, based on this question: Mutate across multiple columns to create new variable sets, i can't divide the A's columns by the mean. I'm trying to do:

df %>%
  mutate(
    across(matches("A"), ~ mean(.x), .names = "mean_{col}"  )
  ) %>%
  mutate(
    across(matches("A"), .names = "adm_A_{col}") / across(matches("mean_"))
  )

What i'm doing wrong?

CodePudding user response:

df %>%
  mutate(across(starts_with('A'), ~./mean(.),.names = "adm_A_{col}"))

  A1 A2 adm_A_A1 adm_A_A2
1  1  4      0.5      0.8
2  2  5      1.0      1.0
3  3  6      1.5      1.2

CodePudding user response:

Please check the below code

df %>%
  mutate(
    across(matches("A"), ~ mean(.x), .names = "mean_{col}"  ), 
    across(starts_with('A'), .names = '{col}_new')/across(starts_with('mean'))
  )

Created on 2023-02-02 with reprex v2.0.2

  A1 A2 mean_A1 mean_A2 A1_new A2_new
1  1  4       2       5    0.5    0.8
2  2  5       2       5    1.0    1.0
3  3  6       2       5    1.5    1.2
  •  Tags:  
  • r
  • Related