How to pass variables that are arguments in user defined functions to subfunctions in r -


i have general problem in understanding how create user defined function can accept variables arguments can manipulated inside defined function. want create function in can pass variables arguments internal functions manipulation. appears many of functions want use require c() operator requires quotes around arguments.

so function has able pass name of variable dataframe quotes c() , other functions requiring quote strings. read through many post on paste0, paste , cat(x), cannot figure out how solve problem completely.

here simple dataset , shortened code structure problem. here want able provide dataframe, , 3 variables. function should provide mean of variable in y position each combo of x , z variable. resultant aggregate table should have names of variables provided arguments xtabar column headers.

n=50 datatest = data.frame(  xcol=sample(1:3, n, replace=true), ycol = rnorm(n, 5, 2), catg=letters[1:5])  xtabar<- function(ds,xcat,yvar,group){    library(plyr)   #library(ggplot2)   #library(dplyr)   #library(scales)   localenv<-environment()   gg<-data.frame(ds,x=ds[,xcat],y=ds[,yvar],z=ds[,group] )   cnames<-colnames(gg)   ag.gg<-aggregate(gg$y, by=list(gg$x,gg$z),fun=mean)    colnames(ag.gg)<-c(cat('"',cnames[1],'"'),cat('"',cnames[2],'"'),cat('"',cnames[3],'"'))   return(ag.gg) }  xtabar(datatest,"xcol","ycol","catg") 

this code close can solving simple problem. don't know how remove quotes column names nor how rid of na's.

thank on logic , or code.

try following. not clear desire quote names put stars around them in code below. if not needed remove setnames statement.

xtabar <- function(ds, xcat, yvar, group) {     ag <- aggregate(ds[yvar], ds[c(xcat, group)], mean)     setnames(ag, paste0("*", names(ag), "*")) } 

test it:

xtabar(datatest, "xcol", "ycol", "catg") 

giving:

   *xcol* *catg*   *ycol* 1       1      5.700938 2       2      5.292628 3       3      5.204395 4       1      b 4.054289 5       2      b 5.119659 6       3      b 4.050799 7       1      c 2.937309 8       2      c 5.696256 9       3      c 6.773029 10      1      d 5.323572 11      2      d 3.430644 12      3      d 4.892041 13      1      e 4.024070 14      3      e 5.038122 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -