In a *for* function, can I keep stacking values?










-1















I currently have lots of excel files with the same fields but for different sectors. I'm trying to create a function that allows me to get the total mean from the "sulfate" field in all my excel sheets.



This is the code I currently have:



Mean_Pollution<-function(directory,pollutant,id = 1:332)
directory <- c("001","002","003","004")
for (x in directory)
print(paste("Reading",x,"file"))
temp = read.csv(paste(directory.path,x,".csv",sep = ""))
print(paste("Finished reading",x,"file"))
i = print(mean(temp$sulfate,na.rm = TRUE))











share|improve this question
























  • Not sure what "stacking" means. Appears that you think directory.path will be operating on the vector directory to give you a set of paths. Not the way R works. Learn to use list.files. I also think the Johns Hopkins Coursera course suggests that you use their website for homework questions. Nonetheless, you will be able to find lots of worked Coursera homework questions with a search on "[r] pollutant". (I just found 290 of them.)

    – 42-
    Nov 14 '18 at 0:36












  • Yes , indeed, but I wanted to fully understand the code. It would be an useful tool if I could apply it to other examples. That's why I brought it here, to see if there was a way for every time an X mean value was given I could catch that value and use it later on.

    – Reinaldo G Rodriguez Malave
    Nov 14 '18 at 0:44











  • You have posted code with no dataset and no description of how that function was being called or what results or errors you might be seeing. So it doesn't make much sense for use to try to offer you advice in he absence of a specific constext.

    – 42-
    Nov 14 '18 at 1:11











  • How are your Excel sheets organized? what is the name of your directory? And what is the id argument for? Why do you use directory.path at all?

    – Evan Friedland
    Nov 14 '18 at 3:29












  • I'm voting to close this question as off-topic because this is a coursera homework question and there are lots of answers on SO. Searching for pollutant on SO will turn up several.

    – phiver
    Nov 17 '18 at 17:27















-1















I currently have lots of excel files with the same fields but for different sectors. I'm trying to create a function that allows me to get the total mean from the "sulfate" field in all my excel sheets.



This is the code I currently have:



Mean_Pollution<-function(directory,pollutant,id = 1:332)
directory <- c("001","002","003","004")
for (x in directory)
print(paste("Reading",x,"file"))
temp = read.csv(paste(directory.path,x,".csv",sep = ""))
print(paste("Finished reading",x,"file"))
i = print(mean(temp$sulfate,na.rm = TRUE))











share|improve this question
























  • Not sure what "stacking" means. Appears that you think directory.path will be operating on the vector directory to give you a set of paths. Not the way R works. Learn to use list.files. I also think the Johns Hopkins Coursera course suggests that you use their website for homework questions. Nonetheless, you will be able to find lots of worked Coursera homework questions with a search on "[r] pollutant". (I just found 290 of them.)

    – 42-
    Nov 14 '18 at 0:36












  • Yes , indeed, but I wanted to fully understand the code. It would be an useful tool if I could apply it to other examples. That's why I brought it here, to see if there was a way for every time an X mean value was given I could catch that value and use it later on.

    – Reinaldo G Rodriguez Malave
    Nov 14 '18 at 0:44











  • You have posted code with no dataset and no description of how that function was being called or what results or errors you might be seeing. So it doesn't make much sense for use to try to offer you advice in he absence of a specific constext.

    – 42-
    Nov 14 '18 at 1:11











  • How are your Excel sheets organized? what is the name of your directory? And what is the id argument for? Why do you use directory.path at all?

    – Evan Friedland
    Nov 14 '18 at 3:29












  • I'm voting to close this question as off-topic because this is a coursera homework question and there are lots of answers on SO. Searching for pollutant on SO will turn up several.

    – phiver
    Nov 17 '18 at 17:27













-1












-1








-1








I currently have lots of excel files with the same fields but for different sectors. I'm trying to create a function that allows me to get the total mean from the "sulfate" field in all my excel sheets.



This is the code I currently have:



Mean_Pollution<-function(directory,pollutant,id = 1:332)
directory <- c("001","002","003","004")
for (x in directory)
print(paste("Reading",x,"file"))
temp = read.csv(paste(directory.path,x,".csv",sep = ""))
print(paste("Finished reading",x,"file"))
i = print(mean(temp$sulfate,na.rm = TRUE))











share|improve this question
















I currently have lots of excel files with the same fields but for different sectors. I'm trying to create a function that allows me to get the total mean from the "sulfate" field in all my excel sheets.



This is the code I currently have:



Mean_Pollution<-function(directory,pollutant,id = 1:332)
directory <- c("001","002","003","004")
for (x in directory)
print(paste("Reading",x,"file"))
temp = read.csv(paste(directory.path,x,".csv",sep = ""))
print(paste("Finished reading",x,"file"))
i = print(mean(temp$sulfate,na.rm = TRUE))








r function for-loop mean






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 0:41









Dean coakley

6871319




6871319










asked Nov 14 '18 at 0:32









Reinaldo G Rodriguez MalaveReinaldo G Rodriguez Malave

11




11












  • Not sure what "stacking" means. Appears that you think directory.path will be operating on the vector directory to give you a set of paths. Not the way R works. Learn to use list.files. I also think the Johns Hopkins Coursera course suggests that you use their website for homework questions. Nonetheless, you will be able to find lots of worked Coursera homework questions with a search on "[r] pollutant". (I just found 290 of them.)

    – 42-
    Nov 14 '18 at 0:36












  • Yes , indeed, but I wanted to fully understand the code. It would be an useful tool if I could apply it to other examples. That's why I brought it here, to see if there was a way for every time an X mean value was given I could catch that value and use it later on.

    – Reinaldo G Rodriguez Malave
    Nov 14 '18 at 0:44











  • You have posted code with no dataset and no description of how that function was being called or what results or errors you might be seeing. So it doesn't make much sense for use to try to offer you advice in he absence of a specific constext.

    – 42-
    Nov 14 '18 at 1:11











  • How are your Excel sheets organized? what is the name of your directory? And what is the id argument for? Why do you use directory.path at all?

    – Evan Friedland
    Nov 14 '18 at 3:29












  • I'm voting to close this question as off-topic because this is a coursera homework question and there are lots of answers on SO. Searching for pollutant on SO will turn up several.

    – phiver
    Nov 17 '18 at 17:27

















  • Not sure what "stacking" means. Appears that you think directory.path will be operating on the vector directory to give you a set of paths. Not the way R works. Learn to use list.files. I also think the Johns Hopkins Coursera course suggests that you use their website for homework questions. Nonetheless, you will be able to find lots of worked Coursera homework questions with a search on "[r] pollutant". (I just found 290 of them.)

    – 42-
    Nov 14 '18 at 0:36












  • Yes , indeed, but I wanted to fully understand the code. It would be an useful tool if I could apply it to other examples. That's why I brought it here, to see if there was a way for every time an X mean value was given I could catch that value and use it later on.

    – Reinaldo G Rodriguez Malave
    Nov 14 '18 at 0:44











  • You have posted code with no dataset and no description of how that function was being called or what results or errors you might be seeing. So it doesn't make much sense for use to try to offer you advice in he absence of a specific constext.

    – 42-
    Nov 14 '18 at 1:11











  • How are your Excel sheets organized? what is the name of your directory? And what is the id argument for? Why do you use directory.path at all?

    – Evan Friedland
    Nov 14 '18 at 3:29












  • I'm voting to close this question as off-topic because this is a coursera homework question and there are lots of answers on SO. Searching for pollutant on SO will turn up several.

    – phiver
    Nov 17 '18 at 17:27
















Not sure what "stacking" means. Appears that you think directory.path will be operating on the vector directory to give you a set of paths. Not the way R works. Learn to use list.files. I also think the Johns Hopkins Coursera course suggests that you use their website for homework questions. Nonetheless, you will be able to find lots of worked Coursera homework questions with a search on "[r] pollutant". (I just found 290 of them.)

– 42-
Nov 14 '18 at 0:36






Not sure what "stacking" means. Appears that you think directory.path will be operating on the vector directory to give you a set of paths. Not the way R works. Learn to use list.files. I also think the Johns Hopkins Coursera course suggests that you use their website for homework questions. Nonetheless, you will be able to find lots of worked Coursera homework questions with a search on "[r] pollutant". (I just found 290 of them.)

– 42-
Nov 14 '18 at 0:36














Yes , indeed, but I wanted to fully understand the code. It would be an useful tool if I could apply it to other examples. That's why I brought it here, to see if there was a way for every time an X mean value was given I could catch that value and use it later on.

– Reinaldo G Rodriguez Malave
Nov 14 '18 at 0:44





Yes , indeed, but I wanted to fully understand the code. It would be an useful tool if I could apply it to other examples. That's why I brought it here, to see if there was a way for every time an X mean value was given I could catch that value and use it later on.

– Reinaldo G Rodriguez Malave
Nov 14 '18 at 0:44













You have posted code with no dataset and no description of how that function was being called or what results or errors you might be seeing. So it doesn't make much sense for use to try to offer you advice in he absence of a specific constext.

– 42-
Nov 14 '18 at 1:11





You have posted code with no dataset and no description of how that function was being called or what results or errors you might be seeing. So it doesn't make much sense for use to try to offer you advice in he absence of a specific constext.

– 42-
Nov 14 '18 at 1:11













How are your Excel sheets organized? what is the name of your directory? And what is the id argument for? Why do you use directory.path at all?

– Evan Friedland
Nov 14 '18 at 3:29






How are your Excel sheets organized? what is the name of your directory? And what is the id argument for? Why do you use directory.path at all?

– Evan Friedland
Nov 14 '18 at 3:29














I'm voting to close this question as off-topic because this is a coursera homework question and there are lots of answers on SO. Searching for pollutant on SO will turn up several.

– phiver
Nov 17 '18 at 17:27





I'm voting to close this question as off-topic because this is a coursera homework question and there are lots of answers on SO. Searching for pollutant on SO will turn up several.

– phiver
Nov 17 '18 at 17:27












1 Answer
1






active

oldest

votes


















0














You seem to have everything you need and there are plenty of questions like this, but I'll provide an example. The assumption here is that everything is in 1 folder. I'll use my own folder:



setwd(dir = "C:/Users/Evan Friedland/Documents")
# Put some fake data in a fake folder
dir.create("Test_Folder")
setwd(dir = "C:/Users/Evan Friedland/Documents/Test_Folder")
n <- 5 # let's write 5 csv files
for(i in 1:n)
write.csv(data.frame(madeupX = LETTERS[sample(1:24, 100, T)], sulfate = rnorm(100)), # fake data
paste0(sprintf("%03d", i), ".csv")) # fake names

csvnames <- paste0(sprintf("%03d", 1:n), ".csv")


Now all you need to do to "stack" the mean of each file is initialize an empty vector, loop through them and save each result to an element of the vector.



means <- numeric(n) # intialize numeric type vector, n long
names(means) <- csvnames # name each element for fun
means <- sapply(1:n, function(x) # used sapply instead of a for loop but either is fine
cat("+ ",csvnames[x],"n") # print which csv is running
mean(read.csv(paste0(csvnames[x]))$sulfate) # return the mean of the sulfate col
)
#+ 001.csv
#+ 002.csv
#+ 003.csv
#+ 004.csv
#+ 005.csv
means # print results
#[1] 0.007859499 0.077447995 0.048796633 -0.101449790 0.224429258





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291477%2fin-a-for-function-can-i-keep-stacking-values%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You seem to have everything you need and there are plenty of questions like this, but I'll provide an example. The assumption here is that everything is in 1 folder. I'll use my own folder:



    setwd(dir = "C:/Users/Evan Friedland/Documents")
    # Put some fake data in a fake folder
    dir.create("Test_Folder")
    setwd(dir = "C:/Users/Evan Friedland/Documents/Test_Folder")
    n <- 5 # let's write 5 csv files
    for(i in 1:n)
    write.csv(data.frame(madeupX = LETTERS[sample(1:24, 100, T)], sulfate = rnorm(100)), # fake data
    paste0(sprintf("%03d", i), ".csv")) # fake names

    csvnames <- paste0(sprintf("%03d", 1:n), ".csv")


    Now all you need to do to "stack" the mean of each file is initialize an empty vector, loop through them and save each result to an element of the vector.



    means <- numeric(n) # intialize numeric type vector, n long
    names(means) <- csvnames # name each element for fun
    means <- sapply(1:n, function(x) # used sapply instead of a for loop but either is fine
    cat("+ ",csvnames[x],"n") # print which csv is running
    mean(read.csv(paste0(csvnames[x]))$sulfate) # return the mean of the sulfate col
    )
    #+ 001.csv
    #+ 002.csv
    #+ 003.csv
    #+ 004.csv
    #+ 005.csv
    means # print results
    #[1] 0.007859499 0.077447995 0.048796633 -0.101449790 0.224429258





    share|improve this answer



























      0














      You seem to have everything you need and there are plenty of questions like this, but I'll provide an example. The assumption here is that everything is in 1 folder. I'll use my own folder:



      setwd(dir = "C:/Users/Evan Friedland/Documents")
      # Put some fake data in a fake folder
      dir.create("Test_Folder")
      setwd(dir = "C:/Users/Evan Friedland/Documents/Test_Folder")
      n <- 5 # let's write 5 csv files
      for(i in 1:n)
      write.csv(data.frame(madeupX = LETTERS[sample(1:24, 100, T)], sulfate = rnorm(100)), # fake data
      paste0(sprintf("%03d", i), ".csv")) # fake names

      csvnames <- paste0(sprintf("%03d", 1:n), ".csv")


      Now all you need to do to "stack" the mean of each file is initialize an empty vector, loop through them and save each result to an element of the vector.



      means <- numeric(n) # intialize numeric type vector, n long
      names(means) <- csvnames # name each element for fun
      means <- sapply(1:n, function(x) # used sapply instead of a for loop but either is fine
      cat("+ ",csvnames[x],"n") # print which csv is running
      mean(read.csv(paste0(csvnames[x]))$sulfate) # return the mean of the sulfate col
      )
      #+ 001.csv
      #+ 002.csv
      #+ 003.csv
      #+ 004.csv
      #+ 005.csv
      means # print results
      #[1] 0.007859499 0.077447995 0.048796633 -0.101449790 0.224429258





      share|improve this answer

























        0












        0








        0







        You seem to have everything you need and there are plenty of questions like this, but I'll provide an example. The assumption here is that everything is in 1 folder. I'll use my own folder:



        setwd(dir = "C:/Users/Evan Friedland/Documents")
        # Put some fake data in a fake folder
        dir.create("Test_Folder")
        setwd(dir = "C:/Users/Evan Friedland/Documents/Test_Folder")
        n <- 5 # let's write 5 csv files
        for(i in 1:n)
        write.csv(data.frame(madeupX = LETTERS[sample(1:24, 100, T)], sulfate = rnorm(100)), # fake data
        paste0(sprintf("%03d", i), ".csv")) # fake names

        csvnames <- paste0(sprintf("%03d", 1:n), ".csv")


        Now all you need to do to "stack" the mean of each file is initialize an empty vector, loop through them and save each result to an element of the vector.



        means <- numeric(n) # intialize numeric type vector, n long
        names(means) <- csvnames # name each element for fun
        means <- sapply(1:n, function(x) # used sapply instead of a for loop but either is fine
        cat("+ ",csvnames[x],"n") # print which csv is running
        mean(read.csv(paste0(csvnames[x]))$sulfate) # return the mean of the sulfate col
        )
        #+ 001.csv
        #+ 002.csv
        #+ 003.csv
        #+ 004.csv
        #+ 005.csv
        means # print results
        #[1] 0.007859499 0.077447995 0.048796633 -0.101449790 0.224429258





        share|improve this answer













        You seem to have everything you need and there are plenty of questions like this, but I'll provide an example. The assumption here is that everything is in 1 folder. I'll use my own folder:



        setwd(dir = "C:/Users/Evan Friedland/Documents")
        # Put some fake data in a fake folder
        dir.create("Test_Folder")
        setwd(dir = "C:/Users/Evan Friedland/Documents/Test_Folder")
        n <- 5 # let's write 5 csv files
        for(i in 1:n)
        write.csv(data.frame(madeupX = LETTERS[sample(1:24, 100, T)], sulfate = rnorm(100)), # fake data
        paste0(sprintf("%03d", i), ".csv")) # fake names

        csvnames <- paste0(sprintf("%03d", 1:n), ".csv")


        Now all you need to do to "stack" the mean of each file is initialize an empty vector, loop through them and save each result to an element of the vector.



        means <- numeric(n) # intialize numeric type vector, n long
        names(means) <- csvnames # name each element for fun
        means <- sapply(1:n, function(x) # used sapply instead of a for loop but either is fine
        cat("+ ",csvnames[x],"n") # print which csv is running
        mean(read.csv(paste0(csvnames[x]))$sulfate) # return the mean of the sulfate col
        )
        #+ 001.csv
        #+ 002.csv
        #+ 003.csv
        #+ 004.csv
        #+ 005.csv
        means # print results
        #[1] 0.007859499 0.077447995 0.048796633 -0.101449790 0.224429258






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 3:53









        Evan FriedlandEvan Friedland

        2,0991621




        2,0991621



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291477%2fin-a-for-function-can-i-keep-stacking-values%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            ReactJS Fetched API data displays live - need Data displayed static

            Evgeni Malkin