I have a general problem in understanding how to create a user defined function that can accept variables as arguments that can be manipulated inside the defined function. I want to create a function in which I can pass variables as arguments to internal functions for manipulation. It appears that many of the functions I want to use require the c()
operator which requires quotes around the arguments.
So my function has to be able to pass the name of a variable from a dataframe into the quotes for c()
and other functions requiring quote strings. I read through many post on paste0
, paste
and cat(x)
, but I cannot figure out how to solve my problem completely.
Here is a simple dataset and shortened code to help structure the problem. Here I just want to be able to provide a dataframe, and three variables. The function should provide the mean of the variable in the y position for each combo of the x
and z
variable. The resultant aggregate table should have the names of the variables provided as arguments to XTABAR as 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 is as close as I can get to solving the simple problem. I don't know how to remove the quotes from the column names nor how to get rid of the NA's.
Thank you for any help on the logic and or code.