Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(R) for loop for a data frame not working

I am trying to create a data frame using a for-loop, since I want to update the rows in the data frame with a new element on each iteration. However, only the last value is printed into the data frame.

I have tried to read different files into a data frame, and then use 'cbind' to match the entry-number of the data file to the number of, in this case, complete cases in a file. The code works for a single entry, but I cannot get the for loop to add all the different rows together; it seems to copy the second iteration over the first, and so on.

complete cases

complete <- function(directory, id) {

    fileList <- dir(directory, full.names = TRUE);
    frame <- data.frame();

    for (i in seq_along(id)) {

        data <- complete.cases(read_csv(fileList[i]));
        frame <- cbind(i, sum(data));
    }

}

As such, I want to obtain a data frame that lists the different files in the directory specified, along with the number of complete cases. Can you tell me what I am doing wrong in this for-loop?

like image 646
alexanderjansma Avatar asked Apr 19 '26 00:04

alexanderjansma


1 Answers

Since you always overwrite your dataframe frame in your loop, you need to cbind it too.

complete <- function(directory, id) {

    fileList <- dir(directory, full.names = TRUE);
    frame <- data.frame();

    for (i in seq_along(id)) {

        data <- complete.cases(read_csv(fileList[i]));
        frame <- cbind(frame, i, sum(data));
    }

}

otherwise your frame gets set every new iteration. So if you want to add it to your frame, you have to give the frame also as input

like image 148
mischva11 Avatar answered Apr 20 '26 13:04

mischva11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!