Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-Function, formals object defined but not found by code

The business I work for does ELISA analysis all the time (the immune assay), and so I am programming a function that takes a csv format version of the machine readout for the optical densities and runs a statistical regression called a 4PL analysis. It is essentially a 4pl for dummies function that makes use of the drc package. I have most of the code written, but now I am attempting to actually put it IN to a function format (it runs fine outside of function structure).

Here is my problem. I am defining the formals() of my function like so:

elisa<-function(file="data.csv",wd="~/Desktop",standards=c(1,2),orient=horizontal,
limit=TRUE,graph.4pl=FALSE,Conc.graph=FALSE){ body of function}

It's not particularly important what the other formals are at the moment, but I am running into two problems. Here is the code for the first part of the block.

rm(list=ls())
setwd(wd)
library(drc);library(reshape2);library(ggplot2)

data<-read.csv(file,head=TRUE, colClasses=c("character"))

If the community in its wisdom thinks I need to include more, I will, but let's leave it there for now.

The problem:

elisa("Mock data.csv")
Error in setwd(wd[1]) : object 'wd' not found

This error shows up. As you can see though, wd IS defined

formals(elisa)
$file
[1] "data.csv"

$wd
[1] "~/Desktop"

$standards
c(1, 2)

$orient
horizontal

$limit
[1] TRUE

$graph.4pl
[1] FALSE

$Conc.graph
[1] FALSE

Moreover, if I predefine wd as "~/Desktop" in the global environment, the error for wd goes away, but I get this

wd<-"~/Desktop"
elisa("Mock data.csv")
Error in read.table(file = file, header = header, sep = sep, quote = quote,  : 
 'file' must be a character string or connection

Either I am completely tanking on how I am defining my formals, or I am running into some very odd argument passing issues. Any ideas?

like image 935
Eich Avatar asked Aug 07 '15 01:08

Eich


1 Answers

The problem is you're deleting all of your formals with the first line, rm(list=ls()).

For example:

f <- function(a=1) {
  rm(list=ls())
  print(a)
}
f()
## Error in print(a) : object 'a' not found

When you define wd in the global environment (i.e. in the stack above your function) your function will work (at least up until that point) because rm(list=ls()) will only delete the variables within your current environment (i.e. the function call stack). In this case, your function will use values for variables defined in the global environment.

like image 99
Scott Ritchie Avatar answered Nov 15 '22 01:11

Scott Ritchie