Skip to content
Prev 55099 / 398500 Next

Accesing the name of an assigned object in a function

Arne Henningsen <ahenningsen <at> email.uni-kiel.de> writes:
As far as I know you are going to have to pass the assigned.name to the
function although there are a number of tricks that can make this a bit
nicer.  For example, run this:

example(lm)

# which has the effect of defining lm.D9 which we will use for our
# examples below.  Using that:

#### 1
set1 <- function(x, value) {
	name <- as.character(substitute(x))
	print(summary(value)$fstatistic)
	cat("That was F and df.  For more info type", name, "\n")
	assign(name, value, parent.frame())
	invisible(value)
}
set1(x, lm.D9)
x
	
# We can make this a bit prettier this way:

#### 2
set2 <- structure(NA,class="set2")
"[<-.set2" <- function(tmp,x,value) {
	name <- as.character(substitute(x))
	print(summary(value)$fstatistic)
	cat("That was F and df.  For more info type", name, "\n")
	assign(name, value, parent.frame())
	tmp
}

# now we can write:
set2[xx] <- lm.D9
xx

# Another strategy might be to use a global variable to store the
# last output from your function:

#### 3
set3 <- function(value) {
	name <- as.character(substitute(x))
	print(summary(value)$fstatistic)
	cat("That was F and df.  For more info type .set3\n")
	assign(".set3", value, .GlobalEnv)
	invisible(value)
}
xxx <- set3(lm.D9)  # or just set3(lm.D9)
.set3