I am not sure if this is a silly question, but I need a hint now. Apologies in advance.
So I have a random dataframe df and I want to use the mutate_at()
function.
x1<-rpois(20,5)
x2<-rpois(20,5)
x3<-rpois(20,2)
df1<-data.frame(x1,x2,x3)
This work perfectly fine if I divide the whole dataframe by one column like this:
library(dplyr)
df1%>%mutate_at(vars(x1:x3),list(All_by_x3=~./x3))
But what I actually want, is that x3
is divided by each column of the dataframe. So I want x3
as the numerator and loop through the different columns in the denominator. What I logically tried is this:
df1%>%mutate_at(vars(x1:x3),list(All_by_x3= x3/ ~.))
but it doesn't work. It feels like there is a simple answer, but I can't see it.
Thanks for any help.
CodePudding user response:
A possible solution, based on dplyr
:
library(dplyr)
df1 %>%
mutate(across(x1:x2, ~ x3/.x, .names = "x3_{.col}"))
#> x1 x2 x3 x3_x1 x3_x2
#> 1 2 4 1 0.5000000 0.25000000
#> 2 7 3 2 0.2857143 0.66666667
#> 3 8 11 1 0.1250000 0.09090909
#> 4 7 4 2 0.2857143 0.50000000
#> 5 3 7 0 0.0000000 0.00000000
#> 6 6 6 3 0.5000000 0.50000000
#> 7 2 7 2 1.0000000 0.28571429
#> 8 7 6 1 0.1428571 0.16666667
#> 9 1 5 0 0.0000000 0.00000000
#> 10 4 7 6 1.5000000 0.85714286
#> 11 3 4 2 0.6666667 0.50000000
#> 12 4 3 2 0.5000000 0.66666667
#> 13 2 1 2 1.0000000 2.00000000
#> 14 2 4 0 0.0000000 0.00000000
#> 15 6 4 1 0.1666667 0.25000000
#> 16 5 5 4 0.8000000 0.80000000
#> 17 7 5 6 0.8571429 1.20000000
#> 18 5 4 3 0.6000000 0.75000000
#> 19 6 5 3 0.5000000 0.60000000
#> 20 5 3 1 0.2000000 0.33333333