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 <- 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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With