Leonhardt Guass
Leonhardt Guass

Reputation: 793

Apply a same function to each column with tidyverse and mutate_all

I have the following data frame

df <- data.frame(total=100,a=5,b=5)

I want to apply a same function to each columns. For example, divide all columns by dividing the first column

df <- df/df$total

However, I want to do it with mutate_all

My code is like this

df <- data.frame(total=100,a=5,b=5) %>% mutate_all(list(~./total))

Which is not giving me the desired output. What am I doing wrong?

Upvotes: 3

Views: 474

Answers (1)

Marius
Marius

Reputation: 60230

total is the first column in your dataframe, and in mutate_all it gets divided by total first, becoming 1. Then the other columns are just divided by 1. If total was the last column instead I think your syntax would work, but it might not be safe to rely on that. It's probably better to use mutate_at and exclude total to avoid this:

data.frame(a=5,b=5,total=100) %>% 
    mutate_at(vars(-total), list(~./total))

Upvotes: 6

Related Questions