JohnDong
JohnDong

Reputation: 49

R Read files, manipulate file names and write files from/to folder

I have 10 files in a folder, which I have to manipulate. At the moment I do that manually meaning I adapt the script ten times. Now I'm trying to do that automatically.

First I get the file names by this command:

data <- list.files(path=".", pattern=".csv", full.names=TRUE)

Now I have the idea to iterate over the file names by a for-loop.

for(i in data) {
    df <- read.csv("i", header=T)
    df$sum <- sum(df$value1, df$value2)
    write.table(df, file=i, row.names=FALSE)
}

I'm not sure if the read.csv command works. Moreover, t I don't want to rewrite the file. The originally file names have the following structure

30LOV_1.csv
30LOV_2.csv
100LOV_1.csv
2000LOV_1.csv

I want to add something like _20min to the file names, e.g.

30LOV_1_20min.csv
30LOV_2_20min.csv
100LOV_1_20min.csv
2000LOV_1_20min.csv

How can I achieve this? Do you have any suggestions?

Thanks

Upvotes: 1

Views: 78

Answers (1)

jasbner
jasbner

Reputation: 2283

You can use sub to add additional information to the end of your filename. I used parenthesis to create a captured group to get the first part of the file name (.*) and then recalled it in the second part with \\1.

for(i in data) {
df <- read.csv("i", header=T)
df$sum <- sum(df$value1, df$value2)
filename <- sub("(.*).csv","\\1_20min.csv",i)
filename
# [1] "30LOV_1_20min.csv"
write.table(df, file=filename, row.names=FALSE)
}

Upvotes: 1

Related Questions