Skip to content

Functional Programming Problem Using purr and R's data.table shift function

2 messages · Michael Lachanski, Dénes Tóth

#
D?nes, thank you for the guidance - which is well-taken.

Your side note raises an interesting question: I find the piping %>%
operator readable. Is there any downside to it? Or is the side note meant
to tell me to drop the last: "%>% `[`"?

Thank you,


==
Michael Lachanski
PhD Student in Demography and Sociology
MA Candidate in Statistics
University of Pennsylvania
mikelach at sas.upenn.edu
On Sat, Dec 31, 2022 at 9:22 AM D?nes T?th <toth.denes at kogentum.hu> wrote:

            

  
  
#
Hi Michael,

R returns the result of the last evaluated expression by default:
```
add_2 <- function(x) {
   x + 2L
}
```

is the same as and preferred over
```
add_2_return <- function(x) {
   out <- x + 2L
   return(out)
}
```

In the idiomatic use of R, one uses explicit `return` when one wants to 
break the control flow, e.g.:
```
add_2_if_number <- function(x) {
   ## early return if x is not numeric
   if (!is.numeric(x)) {
     return(x)
   }
   ## process otherwise (usually more complicated steps)
   ## note: this part will not be reached for non-numeric x
   x + 2L
}
```

So yes, you should drop the last "%>% `[`" altogether as `[.data.table` 
already returns the whole (modified) data.table when `:=` is used.

Side note:: If you use >=R4.1.0 and you do not use special features of 
`%>%`, try the native `|>` operator first (see `?pipeOp`). 1) You do not 
depend an a user-contributed package, and 2) it works at the parser level.

Cheers,
Denes
On 1/2/23 18:59, Michael Lachanski wrote: