2021-06-30

Best way to iterate through an argument of a userfunction which is representing a data variable

Good evening,

I would like to save some time in the future and automate the application of a user function in the future.

The data contains different observations (rows) which consist of a grouping and multiple other variables. It looks something like this df:

df <- data.frame(obs=c(1,2,3,4,5,6,7,8),
                 group=c("a","a","b","a","b","c","a","b"),
                 var1=c(1,1,2,1,3,1,1,2),
                 var2=c(1,2,3,3,2,1,4,5),
                 var3=c(5,4,3,1,2,3,2,5),
                 var4=c(4,5,4,2,3,4,5,3))

I wrote a user function foo_1 to evaluate the occurrence of attributes in each variable with optional grouping. The function also allows to just return the result or to write it to a file.

library(tidyverse)

foo_1 <- function(DF,VAR,grouping=FALSE,char=c(1,2,3,4,5),save=FALSE,name=NULL){
  tostring<-function (some_variable, name=deparse(substitute(some_variable))) {
    return(str_remove(name,"~"))}
    
    Obj <- DF %>% 
      select(group,) %>% 
      {if (grouping) group_by(.,group) else .} %>% 
      count() %>% 
      rename("Variable"=) %>% 
      complete(Variable=char,fill=list(n=0)) # can't use `complete(=char,fill=list(n=0))` for whatever reason
    
    if (save & !is.null(name)){
      message(paste0("Writing file to ","./",name))
      #write.csv2(Obj,paste0("./",name)) #deactivated since it is not really necessary for the mwe I guess
      message("File has been saved.")
    }
    
    else if (save & is.null(name)) {
      message("Showing preview of file..:")
      print(Obj)
      message("What name should be used to save the file? (incl. file format)")
      name <- scan(n=1,what="character")
      message(paste0("Writing file to ","./",name))
      #write.csv2(Obj,paste0("./",name)) #deactivated since it is not really necessary for the mwe I guess
      message("File has been saved.")
    }
    
    else {
      return(Obj)
    }
    
}

The function itselfs works:

> df %>% 
+   foo_1(VAR=var1,save=TRUE,name="test_var1.csv")
Writing file to ./test_var1.csv
File has been saved.

I now would like to iterate though the variables of the df as argument VAR to function foo_1. My approach with a for loop just returns an error message:

> for (i in paste0("var",1:4)){
+   df %>% 
+     foo_1(,save=TRUE,name=paste0("test_",,".csv"))
+ }
 Fehler: Can't rename columns that don't exist.
x Column `var1` doesn't exist.

Probably the way I'am referencing to the data variable is not the best for this purpose?



from Recent Questions - Stack Overflow https://ift.tt/3drRE0x
https://ift.tt/eA8V8J

No comments:

Post a Comment