R: specifying variable name in function parameter for a function of general (universal) use

后端 未结 3 657
慢半拍i
慢半拍i 2021-01-01 05:23

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:         


        
3条回答
  •  清歌不尽
    2021-01-01 05:59

    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.

提交回复
热议问题