Understanding do.call () of paste processing compared to the function (x) paste (x) "on data lines

I am confused how do.call works.

dat <- data.frame(v1 = c("a", "a", "b", "b"),
                  v2 = c("a", "b", "a", "b"), 
                  stringsAsFactors = FALSE)

Why does this seem to go one line at a time

do.call(paste, dat)
[1] "a a" "a b" "b a" "b b"

But it is not

do.call(function(x) paste(x), dat)
Error in (function (x)  : 
  unused arguments (v1 = c("a", "a", "b", "b"), v2 = c("a", "b", "a", "b"))

The function I want to use is

paste_ <- function(x) paste(unique(sort(x)), collapse = "_")

I understand that I can just use applyit to get what I want, but I tried to understand what I was doing do.call.

apply(vars_comb, 1, paste_)
+4
source share
1 answer

The input for do.call is a list, and dataframes are lists. So do.call(paste, dat)equivalently:

paste(v1=dat$v1, v2=dat$v2)

While the function you defined only accepts the parameter "x". Thus, the second part is equivalent:

my_paste <- function(x) paste(x)
my_paste(v2=dat$v1, v1=dat$v2)

Which gives you the same error because v1 and v2 are not defined.

, :

do.call(function(...) paste(...), dat)
0

Source: https://habr.com/ru/post/1681748/


All Articles