1

I have a function and I would like to add two variables into each entry in my list. I have tried a few ways, but I am unsuccessful.

objs <- mget(ls("package:base"), inherits = TRUE) 
funs <- Filter(is.function, objs)
funs <- funs[1:3]

ArgLength <- function(functions){
  out <- vector(mode ="list", length = length(functions))
  for (i in seq_along(functions)) {
    name <- names(functions)[i]
    names(out)[[i]] <- name
    out[[i]] <- c(length(formals(args(functions[[name]]))),  is.primitive(functions[[name]]))
  }
  out 
}

ArgLength(funs)

I also tried to use.

names(out)[[i]] <- name
        out[[i]][1] <- length(formals(args(functions[[name]])))
        out[[i]][2] <- is.primitive(functions[[name]]))

In both cases I end up getting one item for each of the entries in my list.

I end up getting this.

$`-`
[1] 2 1

$`-.Date`
[1] 2 0

$`-.POSIXt`
[1] 2 0

And I'd like to get this.

$`-`
[1] 2 
[2] 1

$`-.Date`
[1] 2 
[2] 0

$`-.POSIXt`
[1] 2 
[2] 0

Per the comment, I updated the loop to include

out[[i]] <- list( length = length(formals(args(functions[[name]]))),  
                 is.prim = is.primitive(functions[[name]]))
names(out)[[i]] <- name

I get this as a sample of the output.

$sprintf
$sprintf$length
[1] 2

$sprintf$is.prim
[1] FALSE

This is the output from str(ArgLength(funs))

List of 3
 $ -       :List of 1
  ..$ : int [1:2] 2 1
 $ -.Date  :List of 1
  ..$ : int [1:2] 2 0
 $ -.POSIXt:List of 1
  ..$ : int [1:2] 2 0
  • Probably replace c with list in the final statement of your for loop. I would probably reverse the second and third lines as well. – lmo Apr 16 at 0:40
  • I'm still looking to get a [1] item and a [2] item. – ivan Apr 16 at 0:46
  • I'm really confused what you're trying to do. Can you make a reproducible example of the specific thing you want to do? Are you just trying to go from list(a=1, b=2, c=3) to list(a=c(1,2), b=c(2,3), c=c(3,5))? – divibisan Apr 16 at 0:50
  • I added the line funs[1:3] to make it reproducible. I'd like that as my input and to create a list where the name of each component is the function name, the first item is the number of arguments and the second item is a TRUE / FALSE for whether it is a primitive function. I include the intended output under and i'd like to get this – ivan Apr 16 at 1:16
  • I guess I'm still confused as to the difference between the two. For each item of the list, you're getting the same values you want. Is the issue that they're a vector, when you want a named list? Can you show str of the output you get? – divibisan Apr 16 at 1:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.