Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this happen when a user-defined R function does not return a value?

Tags:

r

dplyr

plotly

In the function shown below, there is no return. However, after executing it, I can confirm that the value entered d normally.

There is no return. Any suggestions in this regard will be appreciated.

Code

#installed plotly, dplyr
accumulate_by <- function(dat, var) {
  var <- lazyeval::f_eval(var, dat)
  lvls <- plotly:::getLevels(var)
  dats <- lapply(seq_along(lvls), function(x) {
  cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
  })
dplyr::bind_rows(dats)
}


d <- txhousing %>%
  filter(year > 2005, city %in% c("Abilene", "Bay Area")) %>%
  accumulate_by(~date)
like image 404
Ungurrer Avatar asked Dec 31 '25 13:12

Ungurrer


1 Answers

In the function, the last assignment is creating 'dats' which is returned with bind_rows(dats) We don't need an explicit return statement. Suppose, if there are two objects to be returned, we can place it in a list


In some languages like python, for memory efficiency, generators are used which will yield instead of creating the whole output in memory i.e. Consider two functions in python

def get_square(n):
    result = []
    for x in range(n):
        result.append(x**2)
return result

When we run it

get_square(4)
#[0, 1, 4, 9]

The same function can be written as a generator. Instead of returning anything,

def get_square(n):
    for x in range(n):
        yield(x**2)

Running the function

get_square(4) 
#<generator object get_square at 0x0000015240C2F9E8> 

By casting with list, we get the same output

list(get_square(4))
#[0, 1, 4, 9]
like image 134
akrun Avatar answered Jan 03 '26 02:01

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!