Reputation: 107
I need help editing multiple csv's within a folder. I need to count the number of rows in each file, and add a new column to the files. The new column should have the number of rows as the first row in the column, and then descend by 1 for each subsequent row.
Current:
ID V1 V2 V3
1 0.4625 0.917
2 0.9324 0.248
3 0.6691 0.781
4 0.1935 0.330
Proposed:
ID V1 V2 V3 newcol
1 0.4 25 0.9 5
2 0.9 24 0.2 4
3 0.6 91 0.7 3
4 0.1 5 0.3 2
5 0.2 44 0.5 1
Anyone have any ideas? I've been playing around with the terminal and trying to do it that way. I also have some minor experience with r. I'm also using a mac if that helps.
Thanks!
Upvotes: 1
Views: 164
Reputation: 107
Got it! With akrun's guidance I was able to successfully add a column to each csv, with the rows in the new column in descending order. I was then able to write it back to the original files!
filenames <- list.files(path=".../pathoffolder", pattern=".*csv")
for(i in filenames) {
filepath <- file.path(".../pathoffolder", paste(i))
assign(i,filepath)
df <- read.csv(filepath)
df$newcol <- rev(seq_len(nrow(df)))
write.csv(df, filepath, quote = FALSE, row.names = FALSE)
}
Upvotes: 1
Reputation: 887951
We can do
df1$newcol <- rev(seq_len(nrow(df1)))
Or
df1$newcol <- nrow(df1):1
Upvotes: 2