How to generalize union () to accept N arguments?

How can I add / paste data in uniondynamically?

For example, I have 4 datasets to combine,

mydata <- union(data1, data2, data3, data4)

But sometimes I have less than 4, and sometimes more.

Any ideas how I can solve this problem?

+4
source share
2 answers

Make some reproducible data:

#dummy data
data1 <- data.frame(x=letters[1:3])
data2 <- data.frame(x=letters[2:4])
data3 <- data.frame(x=letters[5:7])

We can use rbindc uniquein the line and then evaluate:

#get list of data frames to merge, update pattern as needed
data_names <- ls()[grepl("data\\d",ls())]
data_names <- paste(data_names,collapse=",")

#make command string
myUnion <- paste0("unique(rbind(",data_names,"))")

#evaluate
eval(parse(text=myUnion))

EDIT:

Here is another better / simpler way do.call::

unique(do.call("rbind",lapply(objects(pattern="data\\d"),get)))
+4
source

You can flip your own function, for example vunion, described below. Not sure if this really works, my [R] is a bit outdated;)

, (, ...) , . 2 , , , .

vunion <- function(...){
  data <- list(...)
  n <- length(data)
  if(n > 2){
    u <- list(t(union(data[[1]], data[[2]])))
    return(do.call(vunion, as.list(c(tail(data, -2), u))))
  } else {
    return(union(data[[1]], data[[2]]))
  }
}
+2

All Articles