Reputation: 29
I have a data frame containing many columns of different classes, I'm including a very simplified example below:
df <- data.frame( col1=c("mary", "john", "luke", "peter", "agnes", "anne", "july", "judy", "tina", "ben"),
col2=c(0.1111,0.3123,0.7875,0.6789,0.87862,0.37512,0.69875,0.1785,0.1777, 0.9999),
col3=c(0.1111,0.3123,0.7875,0.6789,0.87862,0.37512,0.69875,0.1785,0.1777, 0.9999),
col3=c(124.6, 763.8, 222.9, 765.0, 564.7, 761.8, 683.9, 655.9, 897.3, 566.1))
I would like to round off all of the numeric columns, but to different values. For example: col2 and col3 should be rounded off to 2 digits and col4 to 0 digits.
The style of code I was able to come up with is something like this:
df2 <- df %>% mutate_at(2, round, 2)
df3 <- df2 %>% mutate_at(3, round, 2)
df4 <- df3 %>% mutate_at(4, round, 0)
If I don't assign the value to a new data frame each time around it doesn't save the values to my data frame. For instance if I do something like this:
df %>% mutate_at(2, round, 2)
df %>% mutate_at(3, round, 2)
df %>% mutate_at(4, round, 0)
It writes out the desired output to the console, but doesn't save it to df. I was wondering if there was more elegant and intuitive way of doing this?
Upvotes: 0
Views: 360
Reputation: 388907
_at
, _all
, _if
variants are now superseded by across
which also allows you to input multiple operations in the same mutate
pipe.
library(dplyr)
df <- df %>%
mutate(across(2:3, round, 2),
across(4, round, 0))
df
# col1 col2 col3 col3.1
#1 mary 0.11 0.11 125
#2 john 0.31 0.31 764
#3 luke 0.79 0.79 223
#4 peter 0.68 0.68 765
#5 agnes 0.88 0.88 565
#6 anne 0.38 0.38 762
#7 july 0.70 0.70 684
#8 judy 0.18 0.18 656
#9 tina 0.18 0.18 897
#10 ben 1.00 1.00 566
Upvotes: 1
Reputation: 655
You can keep using the pipe operator to connect the code together.
df <- df %>%
mutate_at(c(2, 3), round, 2) %>%
mutate_at(4, round, 0)
Upvotes: 2