Rich Scriven Rich Scriven - 1 year ago 33
R Question

within.list() versus within.data.frame() - What's the difference?

Upon investigating

within()
, I noticed it uses methods for lists and data frames.

within
# function (data, expr, ...)
# UseMethod("within")
# <bytecode: 0x4403f78>
# <environment: namespace:base>
methods("within")
# [1] within.data.frame within.list
# see '?methods' for accessing help and source code


Reading through the code for each
within.list()
and
within.data.frame()
, I noticed they are exactly the same. This is confirmed by

identical(within.list, within.data.frame)
# [1] TRUE


They also seem to act the same, and do exactly the same thing. Take these two examples:

x <- list(a = 1:5, b = 6:10)
identical(
within.list(x, { d <- 11:15 }),
within.data.frame(x, { d <- 11:15 })
)
# [1] TRUE
y <- as.data.frame(x)
identical(
within.list(y, { d <- 11:15 }),
within.data.frame(y, { d <- 11:15 })
)
# [1] TRUE


Is there an actual difference between these two functions? If so, what is it? If not, why do two of exactly the same function exist?

Answer Source

No difference. within.list is an alias for within.data.frame. See the source

within.list <- within.data.frame

Both exist so that if the within generic is called on either a list or a data.frame the proper method will be dispatched.

If within.list didn't exist and you tried to call within(myList, ...) you would get an error like

Error in UseMethod("within") : 
  no applicable method for 'within' applied to an object of class "list"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download