0
votes

I have a function similar to this:

testfun = function(jID,kID,d){
  g=paste0(jID,kID)
  date = d
  bb=data.frame(g,date)
  return(bb)
}

Data frame:

x=data.frame(jID = c("a","b"),kID=c("c","d"),date="20170206",stringsAsFactors = FALSE)

I want to pass each row as inputs into the function. The solutions provided here: Passing multiple arguments to a function taken from dataframe are great but in their case, the number of columns was known. How would a solution like this:

vtestfun <- (Vectorize(testfun, SIMPLIFY=FALSE))
vtestfun(x[,1],x[,2],x[,3])

be applied if the number of columns in the dataframe is not known or keeps changing?

1

1 Answers

0
votes

If you can match the argument names to the column names like so:

testfun <- function(jID, kID, date){ # 'date', not 'd'
  g    <- paste0(jID, kID)
  bb   <- data.frame(g, date)
  return(bb)
}

You could do:

purrr::pmap(x, testfun)

Returning:

[[1]]
   g     date
1 ac 20170206

[[2]]
   g     date
1 bd 20170206
# Data used:
x <- structure(list(jID = c("a", "b"), kID = c("c", "d"), date = c("20170206", "20170206")), class = "data.frame", row.names = c(NA, -2L))