Reputation: 99
I have a folder with many csv files and I want to make a function that will receive as an argument a numeric range by which the function will pick the selected files (named 1.csv, 2.csv, etc.) and insert them into one data frame. I tried:
fun <- function(range){
for( i in range){
dat <- read.csv("K:/R program/",i,".csv")
}
dat
}
I have a few problems. First, I'm probably running over the data each iteration. Second, the read function is not working and making error.
Upvotes: 0
Views: 1913
Reputation: 7832
sprintf should work, like eg
for (i in 1:length(urls)) {
download.file(urls[i], sprintf("~/Desktop/rstats/temp%i.csv.gz", i))
}
And to avoid overwriting your data, init the data frame and bind rows in each for-step.
df <- data.frame()
library(dplyr)
for (i in 1:length(urls)) {
df.csv <- read.csv(sprintf("~/Desktop/rstats/temp%i.csv", i))
dummy.df <- df.csv %>% dplyr::select(date, package, version, country)
df <- dplyr::bind_rows(df, dummy.df)
}
Upvotes: 0
Reputation: 174948
There are two problems:
dat
at each iteration, andread.csv()
, not pasting parts of the filename into a single string.The file.path()
function is usually useful here, but it is more convenient to use paste0()
here as you have part of the file name in a variable and the extension needs to be added. I might try (making some assumptions about your data)
fun <- function(range, ...){
dat <- vector(mode = "list", length = length(range))
for (i in seq_along(range)){
path <- paste0("K:/R program", range[i], ".csv")
dat[[i]] <- read.csv(file = path, ...)
}
dat
}
Some explanation, line by line:
i
be an integer index i
= {1, 2, ..., n}paste0()
i
th element of dat
dat
Upvotes: 1