0
votes

I have a function with many arguments:

fun(A,B,C,D,E)

Now I want to assign fixed value a,b,c,d to A,B,C,D and assign E a list of 1 : 7

I want to use do.call() as below, but it doesn't work.

a <- do.call(function(x) fun(A = a, B = b, C = c, D = d, E = x), list(1:7))

I turn to lapply, and it works,

a <- lapply(c(1:7), function(x) fun(A = a, B = b, C = c, D = d, E = x))

As Joshua Ulrich's answer, when I try

a `<- do.call(fun, list(A = a, B = b, C = c, D = d, E = list(1:7)))`

it says

(list) object cannot be coerced to type 'double'

So I guess fun needs a double value for E, but do.call() doesn't give the values one by one, but a list.

I don't want to use lapply because it returns a list of list, which, if I want to point at a special list, I have to use [[]], and only single value is allowed in [[]], and I cannot use a vector to point at, e.g. [[a]],with a <- c(1:7).

How to make do.call() work?

1
Why don't you use lapply since it works? I think you have misunderstood why/how to use do.call - it is not supposed to do the same thing as lapply... Can you provide fun and the desired output? - konvas
@konvas Thanks, I have edit the question, showing why I don't want to use lapply.... for do.call, is it suppose to apply function with different parameters? - 163
OK, so you should keep using lapply but then you can simplify your result, depending on the format you want it to have. For example, you can covert this list x <- list(1, 2, 3) to the vector c(1, 2, 3) simply by unlist(x). It really depends on the format of the output of lapply and what you want to convert it to (sapply does some automatic simplification which may or may not work for you, I tend to avoid it) - konvas
By the way, vector subscripts do work with lists, but with single square bracket. Try for example list(1, 2, 3, 4)[2:3] - konvas
@konvas Thanks, the problem is the result is like this. a <- list(listA,listB,listC), for A,B,C, they are also a list with 6 lists. if I unlist(a)....then all the list will disappear. For my goal is just to get listA (which a[[1]] gives back), not a list of listA (which a[1] gives back).....this really annoys me every time I use lapply. sometime I will use sapply instead, but for this case, sapply cannot get what I want....that's why I turn to do.call() - 163

1 Answers

3
votes

That should be:

a <- do.call(fun, list(A = a, B = b, C = c, D = d, E = list(1:7)))

And I have a feeling you want E to be a vector, not a list, in which case it should be:

a <- do.call(fun, list(A = a, B = b, C = c, D = d, E = 1:7))