2

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?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.