0

How to write a function for the following script in R

The above code is working fine in R studio but seems to be like command line but i need to write a class with functions and objects like we do in java,c++ etc

> data1 <- read.csv("AllMetals.csv")

> sb <- subset(melt(data1, varnames = c("Gold", "Silver", "Bronze"), id.vars = 1:6, value.name = "Count", variable.name = "Metal"), Count > 0)

> write.xlsx(sb, "E:/Alteryxdataout.xlsx")
Gowtham SB
  • 111
  • 1
  • 13
  • Did you your spell check convert `xlsx` to "*class*"? Also, what is the problem you are facing? What isn't working? Finally, please make your problem [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – David Arenburg Mar 13 '15 at 13:20
  • Did you maybe mean "function" rather than "class"? – Dominic Comtois Mar 13 '15 at 13:22
  • The above code is working fine in R studio but seems to be like command line but i need to write a class with functions and objects like we do in java,c++ etc – Gowtham SB Mar 13 '15 at 13:26
  • 1
    @sbgowtham if you want a function, you can try to do it like this sbgowthamfunction <- function(arg1, arg2, ... ){ domyjob return(object) } the arg1, 2 etc are your inputs , and return is your output. I think it is better you provide an example data and write what you exactly want to have –  Mar 13 '15 at 13:36
  • My 2 cents is also that you should get used to working with functions before moving on to classes. – Dominic Comtois Mar 13 '15 at 13:57

1 Answers1

0

Using only 2 arguments (in and out files):

write.xlsx.fun <- function(csv.file = NA, outfile = NA) {
  data1 <- read.csv(csv.file)
  sb <- subset(melt(data1, varnames = c("Gold", "Silver", "Bronze"), 
               id.vars = 1:6, value.name = "Count", variable.name = "Metal"),
               Count > 0)
  write.xlsx(sb, outfile)
}

You can add as many arguments as you need for cutomization... and you can add the librarystatement for your xlsx or XLConnect package inside the function as needed.

Dominic Comtois
  • 10,230
  • 1
  • 39
  • 61