Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function: return assigned argument instead of variable name

Tags:

r

I searched a lot but did not find any answer to my question, even though I am sure it should not be so difficult. The thread that came closest received no answers (How do I access the name of the variable assigned to the result of a function within the function in R?)

In any case, I am trying to do the following: the function should create two objects, z and doc, and return it using the assigned name, and not the variable name. A short example:

fun.docmerge <- function(x, y, z, crit, typ, doc = checkmerge) {
  mergedat <- paste(deparse(substitute(x)), "+",
                    deparse(substitute(y)), "=", z)
  countdat <- nrow(x)
  check_t1 <- data.frame(mergedat, countdat)
  z <- join(x, y, by = crit, type = typ)
  countdat <- nrow(z)
  check_t2 <- data.frame(mergedat, countdat)
  doc <- rbind(doc, check_t1, check_t2)
  return(list(checkmerge = doc, z = z))
}

results <- fun.docmerge(x = df1, y = df2, z = "df3", crit = c("id"), typ = "left")

Some sample data:

df1 <- structure(list(id = c("XXX1", "XXX2", "XXX3", 
"XXX4"), tr.isincode = c("ISIN1", "ISIN2", 
"ISIN3", "ISIN4")), .Names = c("id", "isin"
), row.names = c(NA, 4L), class = "data.frame")

df2 <- structure(list(id= c("XXX1", "XXX5"), wrong= c(1L, 
1L)), .Names = c("id", "wrong"), row.names = 1:2, class = "data.frame")

checkmerge <- structure(list(mergedat = structure(integer(0), .Label = character(0), class = "factor"), 
    countdat = numeric(0)), .Names = c("mergedat", "countdat"
), row.names = integer(0), class = "data.frame")

The problem is that this returns z as z. However, I want it to be returned as df3 (the name assigned as argument). Is there a way to do that? I could easily solve it to return doc as checkmerge. However, z is dynamic so this would not work.

like image 389
deca Avatar asked Sep 17 '26 07:09

deca


1 Answers

Try this

fun.docmerge <- function(x, y, z, crit, typ, doc = checkmerge) {
  mergedat <- paste(deparse(substitute(x)), "+",
                    deparse(substitute(y)), "=", z)
  countdat <- nrow(x)
  check_t1 <- data.frame(mergedat, countdat)
  z1 <- join(x, y, by = crit, type = typ)
  countdat <- nrow(z1)
  check_t2 <- data.frame(mergedat, countdat)
  doc <- rbind(doc, check_t1, check_t2)
  t1<-list()
  t1[["checkmerge"]]<-doc
  t1[[z]]<-z1
  return(t1)
}
like image 194
niths4u Avatar answered Sep 18 '26 20:09

niths4u



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!