Chega
Chega

Reputation: 195

Export columns to separate csv files

I am having this data.frame in R:

df <- structure(list(AA = c(0.3, 0.1, 0.6), BB = c(0.9, 0.4, 0.2),
CC = c(1, 0.8, 0.6), DD = c(0.7, 0.5, 0.5)), .Names = c("AA", "BB", "CC", "DD"), class = "data.frame", row.names = c(NA, -3L))

Now what I need is the columns (AA,BB,CC,DD) written to separate csv files, named after the respective column names (AA.csv, BB.csv, CC.csv, etc).

I am new to R and know how to do this for one column using write.csv, but just don't see how to do this for many columns (looping)...

Upvotes: 0

Views: 3190

Answers (2)

Paul Hiemstra
Paul Hiemstra

Reputation: 60924

I in addition to the for loop of @mdsummer, you can use an apply construction, which is very R-ish :). The general idea is to take subsets of the object you are woking with, and applying a function to each of those subsets. I really like the apply family of functions that the plyr package provides. Something along the lines of this should work (remember to load the plyr package):

l_ply(names(df), function(x) write.csv(df[[x]], paste(x, ".csv", sep = ""))

The name of the plyr function says that the input is a list (l) and that and output of the function is discarded (_). See the paper I linked above for much more detail.

Upvotes: 3

mdsumner
mdsumner

Reputation: 29477

It's easy enough to use a for loop, constructing the file name as you go with ?paste:

for (ci in 1:ncol(df)) {
    write.csv(df[,ci], paste("col", ci, ".csv", sep = ""))
}

Now check that that worked as expected:

list.files(pattern = "csv")

[1] "col1.csv" "col2.csv" "col3.csv" "col4.csv"

Using the ci counter for each column, we subset the data.frame on column and write to CSV, you might want extra options for write.csv, particularly row.names = FALSE. See them all with

(Note, if you don't use row names there's really no need for the commas anyway, are you sure you want a single column CSV file?).

These are all pretty basic R operations so you should review the Introduction to R and each of the R functions and controls used:

?Control 
?Extract
?seq
?ncol
?write.csv
?paste

Upvotes: 4

Related Questions