Reputation: 87
I have many csv files and I need to count the number of rows split by type. An example csv format is
Type,speed
Turtle,10
Lion,50
Cheetah,100
Turtle,12
Lion,70
Cheetah,110
Cheetah,170
So the example output would be:
Type count
turtle 2
lion 2
cheetah 3
I can do this for an individual file using the below R code:
library(dplyr)
##
a1 <- read.csv("data1.csv")
a1 %>%
group_by(Type, Type) %>%
summarise(count=n())
Can someone help me loop this across all csv files? I have data1.csv
to data100.csv
.
Upvotes: 2
Views: 220
Reputation: 70336
As mentioned in the comments you can use list.files
to get a list of the files in your directory:
file_list <- list.files(directory) # pattern omitted since they're the only files
Then read all files into a list:
files <- lapply(file_list, read.csv, header=TRUE)
names(files) <- sub("\\.csv$", "", file_list)
Now, you could do:
res <- lapply(files, function(dat) dplyr::count(dat, Type))
Upvotes: 3