0

Hi I am quite new to R programming. What I want to do is to replicate a series of actions to multiple files. My first step is to create a function that reads a file, and then performs subsequent actions. For example

analyze <- function(filename){data<- read.csv(filename, header=TRUE)
average<- mean(data[,2]) 
print (average)}

analyze ("my first file")

However, I am having a problem with the code, because it does not give the right result. data is not updated when I change the filename. I don't know what went wrong. Can anyone give me a simpler alternative solution? Many thanks.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • 1
    `lapply(files, function(x) mean(analyze(x)[,2]))` – akrun Feb 12 '19 at 14:04
  • 1
    "does not give the right result" What's the result you're expecting? It doesn't look like you're returning anything, just printing the mean. Is that what you intend to do? – camille Feb 12 '19 at 14:11
  • I made some dummy files, ran this function, and was able to print out the means appropriately. If you're having trouble with specific files or data frames, you'll have to post a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for us to see what's going on. I'd also recommend checking your syntax: the line breaks in your function are awkward, and I wonder if you're running code line by line and therefore not getting the entire function to run as a block – camille Feb 12 '19 at 14:22
  • the "analyze" function i made does not work. What I want to do is, for example, I have three files, and I want to delete the 2nd column for each file. is there an easier way to this do this? – nicole chenye Feb 13 '19 at 02:51

0 Answers0