Aegard
Aegard

Reputation: 45

Loop colSum over a list of CSV files in R

Say I have a list of 300 CSV files loaded using:

files <- list.files(".../files", pattern=".csv")

Each CSV file is a 10x10 matrix and I want to loop over each and every file to determine how many columns inside each CSV in which there are exactly 5 instances of a 1

I'm new to R and I'm not sure how to loop this over every file in my list.

Appreciate any help greatly!

Upvotes: 0

Views: 56

Answers (1)

akrun
akrun

Reputation: 887721

We need to read the data probably with read.csv (from base R) or use fread from data.table after looping over the files in lapply, then get the colSums

sapply(files, function(x) sum(colSums(read.csv(x) == 1, na.rm = TRUE) == 5))

data

files <- list.files(".../files", pattern="\\.csv", full.names = TRUE)

Upvotes: 1

Related Questions