1

Here is data:

library(tidyverse)
set.seed(1234)
df1 <- tibble(
  S1 = rnorm(5), 
  S2 = rnorm(5), 
  S3 = rnorm(5), 
  S4 = rnorm(5), 
)

I want to apply an arithmetic transformation, truncate the distribution, and format values as integers. This code works:

df2 <- df1 %>%
  mutate(across(everything(),
                ~
                  round(. * 10) + 50),
         across(
           everything(),
           ~
             case_when(. < 45 ~ 45,
                       . > 55 ~ 55,
                       TRUE ~ .) %>%
             as.integer(.)
         ))

But when I make the code more concise, placing all three operations within a single instance of across(), as in:

df3 <- df1 %>%
  mutate(across(everything(),
                ~
                  round(. * 10) + 50) %>% 
                    case_when(. < 45 ~ 45,
                       . > 55 ~ 55,
                       TRUE ~ .) %>%
             as.integer(.)
         )

I get this error:

Error: Problem with `mutate()` input `..1`.
x Case 1 (`.`) must be a two-sided formula, not a `tbl_df/tbl/data.frame` object.
ℹ Input `..1` is ``%>%`(...)`.

Not sure what I'm doing wrong. Thanks in advance for any help.

DSH
  • 427
  • 2
  • 10

1 Answers1

1

We can place them in a block {}

df1 %>%
    mutate(across(everything(), ~
    (round(. * 10) + 50) %>%
      {case_when(. < 45 ~ 45, . > 55 ~ 55, TRUE ~ .)} %>% 
    as.integer ))
# A tibble: 5 x 4
#     S1    S2    S3    S4
#  <int> <int> <int> <int>
#1    45    55    45    49
#2    53    45    45    45
#3    55    45    45    45
#4    45    45    51    45
#5    54    45    55    55

Or create a temporary object within {} and apply case_when on it

df1 %>%
     mutate(across(everything(), ~ {
         tmp <- round(. * 10 ) + 50
         as.integer(case_when(tmp < 45 ~ 45, tmp > 55  ~ 55, TRUE ~ tmp))
      }))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you. How do the curly braces change how R evaluates the code? I see that it does work, I still don't understand the mechanism. – DSH Jan 17 '21 at 21:21
  • @DSH Can you check [here](https://stackoverflow.com/questions/42623497/when-should-we-use-curly-brackets-when-piping-with-dplyr?noredirect=1&lq=1) – akrun Jan 17 '21 at 21:23
  • 1
    Thanks - that's the explanation I was looking for! – DSH Jan 17 '21 at 21:59