Here is my small function and data. Please note that I want to design a function not personal use for general use.
dataf <- data.frame (A= 1:10, B= 21:
I'm not sure to fully understand your problem, so here is what i understood : you want your function to call the lm() function on data extracted from a data.frame given as an argument, and the columns in this data.frame specified by other arguments ?
To me the simpliest solution is to mimic the lm() behavior and ask the user for a formula :
dataf <- data.frame(A=1:10, B=21:30, C=51:60, D=71:80)
myfun <- function(formula, dataframe) {
daf2 <- data.frame(A=dataframe$A*dataframe$B, B=dataframe$C*dataframe$D)
anv1 <- lm(formula=formula, data=daf2)
print(anova(anv1))
}
myfun(formula=A~B, dataframe=dataf)
An other solution is to build the formula yourself :
dataf <- data.frame(A=1:10, B=21:30, C=51:60, D=71:80)
myfun <- function(dataframe, varA, varB) {
daf2 <- data.frame(A=dataframe$A*dataframe$B, B=dataframe$C*dataframe$D)
frm = as.formula(sprintf("%s~%s", varA, varB))
anv1 <- lm(frm, daf2)
print(anova(anv1))
}
myfun(dataframe=dataf, varA="A", varB="B")
I am not so familiar with attach but i try to avoid it when possible, for masking problems as you mentionned. If you detach it at the end of the function i think it would not cause border effect, but you may raise a warning as well.