read through a loop of csv files and record which files has the maximum number of variables in r

Here is the code snippet to read through a loop of CSV files and record which file has the maximum number of variables in R:

# List all CSV files in a directory
files <- list.files(pattern='\\.csv$')

# Initialize variables to keep track of maximum number of variables and the file name
max_variables <- 0
max_file <- ""

# Iterate over each CSV file
for(file in files) {
    data <- read.csv(file)
    num_variables <- ncol(data)
    
    # Check if current file has more variables than the previous maximum
    if(num_variables > max_variables) {
        max_variables <- num_variables
        max_file <- file
    }
}

# Print the file with the maximum number of variables
print(paste("File with maximum number of variables:", max_file))
print(paste("Number of variables:", max_variables))
668 chars
23 lines

Please note that you may need to adjust the path to the directory containing your CSV files or configure R to point to the correct directory before running this code.

related categories

gistlibby LogSnag