I have a toy function (for illustration use), within the function i have to produce a csv file with the results Here is my function :
# data #
df <- data.frame(ID = c(1, 2), Obs = c(1.0, 2.0), var=c(2.0,5.0))
df
ID Obs var
1 1 1 2
2 2 2 5
# version 1 function
disp <- function(df, c=NULL) {
if(!is.null(c)){
tab_res=data.frame(v1=df$ID*2,v2=df$Obs*3,v3=df$var*c)
}else{
tab_res=data.frame(v1=df$ID*2,v2=df$Obs*3,v3=df$var)
}
result=write.csv(tab_res,"test1.csv")
return(tab_res)
return(result)
}
# current output
disp(df,c=NULL)
v1 v2 v3
1 2 3 2
2 4 6 5
disp(df,c=1)
v1 v2 v3
1 2 3 2
2 4 6 5
disp(df,c=2)
v1 v2 v3
1 2 3 4
2 4 6 10
# it produced also a csv file with exacte tables
What i need is whenever i change an argument in my function, it will produce a different csv file with the appropriate name (chosen by the user). This is what i did, it is working, but i was wondering if there is any other efficient way, in addition i do not see the column names in the csv files (when i try to set col.names
to TRUE, it gives me an error).
# modified function version 2
disp <- function(df, c=NULL, output_name) {
if(!is.null(c)){
tab_res=data.frame(v1=df$ID*2,v2=df$Obs*3,v3=df$var*c)
}else{
tab_res=data.frame(v1=df$ID*2,v2=df$Obs*3,v3=df$var)
}
result=write.csv(tab_res,"test1.csv")
csv_name <- paste0("test1_", output_name, ".csv")
result=write.table( tab_res,
file=csv_name,
append = T,
sep=',',
row.names=F,
col.names=F,
quote=T)
return(tab_res)
return(result)
}
disp(df,c=NULL,"no_c")
v1 v2 v3
1 2 3 2
2 4 6 5
# it produces a csv file test1_no_c
Thank you in advance for your help!