0 votes
1 view
in Data Science by (17.6k points)

I have .csv files in a directory (lets say C:/Dowloads). I am able to read all the files from that directory using the list.files("path"). But I am unable to read a specified number of files using a for loop. That is, lets say I have 332 files and I just want to read only files 1 to 10 or 5 to 10.

Here is an example:

files <- list.files("path")

files ## displays all the files.

Now for testing I did:

k <- files[1:10]

k

## here it displays the files from 1 to 10.

So I kept the same thing using a for loop, as I want to read files one by one.

for(i in 1:length(k)){

  length(i) ## just tested the length 

}

But it is giving as NA or Null or 1.

Can any one explain how can I read specified .csv files using a for loop or any other way?

1 Answer

0 votes
by (40.4k points)

Use nchar  to get the number of characters for each element of the character vector.

So,the code will look like this:

path.to.csv <- "/path/to/your/csv/files"

files<-list.files(path.to.csv)

print(files)  ## list all files in path

k<-files[1:10]

print(k)      ## list first 10 files in path

for(i in 1:length(k)) {  ## loop through the first 10 files

  print(k[i]) ## each file name

  print(nchar(k[i])) ## the number of characters in each file name

  df <- read.csv(paste0(path.to.csv,"/",k[i]))  ## read each as a csv file

  ## process each df in turn here

}

You should also paste the "path" to the file name in calling read.csv.

If you want to learn data science in-depth then enroll for best data science training.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...