Mr.Rlover
Mr.Rlover

Reputation: 2613

Write and name a csv file with the column name of a dataframe

I have a dataframe with one column and 20 rows. I want to save the dataframe to a csv file. I want to use the column name as the file name of the csv file.

I've tried extracting the column name and assigning it in a variable but not sure what to do next. I imagine it would require using paste0 in some way but I can't seem to figure it out.

This is what my data looks like.

df <- data.frame(seq(from=0.05, to=1, by=.05))
colnames(df) <- "2000-03-31"
write.csv(df, file = "2000-03-31.csv", row.names = T)

I want to have a csv file with a file name of 2000-03-31.csv. This works fine with one dataframe but I need to extract the column name and use that as the filename for when I have multiple data frames. Is there a way of doing this programmatically?

Upvotes: 2

Views: 2230

Answers (1)

zx8754
zx8754

Reputation: 56024

Try this:

write.csv(df, file = paste0(colnames(df)[1], ".csv"), row.names = TRUE)

To keep it clear, I like to keep output filenames as a variable:

fileOutput <- paste0(colnames(df)[1], ".csv")
# fileOutput     
# [1] "2000-03-31.csv"

#    
# some codes...
#

write.csv(df, file = fileOutput, row.names = TRUE)

Upvotes: 3

Related Questions