Summarise or mutate + across converts double dbl or integer int to character chr

something curious happens when applying summarise or mutate, where the class of the data changes.

No errors, the outcome class is OK

# Packages
require(NHANES, # the dataset
        tidyverse)


# the dataset
data(NHANES)


# example, no errors
NHANES %>% 
  group_by(Gender) %>% 
  summarise(across(c("Age", "Pulse"), 
                    list(mean, min, max), na.rm = T))

The outcome

screenshoot_Selection_1767

I'm trying to make the numbers have one decimal place. So, when

# example, errors, some columns are CHR now
NHANES %>% 
  group_by(Gender) %>% 
  summarise(across(c("Age", "Pulse"), 
                    list(mean, min, max), na.rm = T)) %>% 
  mutate(across(is.numeric, format, 1))

some columns are CHR instead their original class
screenshoot_Selection_1768

is this a bug or a feature?

1 Like

I believe that format() converts numbers to characters:

> format(123)
[1] "123"
> class(format(123))
[1] "character"

You can use format() to set the decimals and then convert back to numeric:

> as.numeric(format(c(123.4, 123), nsmall = 1))
[1] 123.4 123.0
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.