sirallen
sirallen

Reputation: 1966

Update csv headers in R without re-writing entire file

I'd like to change the column names of a large csv file, and leave the rest as is. Can I do this without re-writing the entire file? My current code is slow:

library(data.table)
da = fread(file)
setnames(da, names(da), tolower(names(da)))
write.csv(da, file, row.names = F)

Upvotes: 2

Views: 234

Answers (1)

maccruiskeen
maccruiskeen

Reputation: 2818

If you can use sed this will be very easy. Here is a sample file:

A,B,C
Foo,Bar,Baz
1,2,3

You want to convert A, B, C to a, b, c. You can do this with:

 sed -e '1s/\(.*\)/\L\1/' test.csv > test-lower.csv

The contents of test-lower.csv is then:

a,b,c
Foo,Bar,Baz
1,2,3

Upvotes: 3

Related Questions